<?php

namespace App\Http\Resources;

use App\Models\ServicePackageItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ScheduleResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $servicePackageId = $this->service_package_id ?? ServicePackageItem::query()
            ->where('schedule_id', $this->id)
            ->value('service_package_id');

        $servicePackageItemsCount = $this->service_package_items_count ?? (
            $servicePackageId
                ? ServicePackageItem::query()
                    ->where('service_package_id', $servicePackageId)
                    ->whereHas('schedule', fn ($query) => $query
                        ->whereNotIn('status', ['cancelled', 'rejected'])
                        ->where('schedule_type', 'default'))
                    ->count()
                : 0
        );

        return [
            'id'            => $this->id,
            'client_id'     => $this->client_id,
            'client_name'   => $this->client?->user?->name,
            'provider_id'   => $this->provider_id,
            'provider_name' => $this->provider?->user?->name,
            'gender'        => $this->provider?->gender?->value,
            'gender_label'  => $this->provider?->gender?->label(),
            'address_id'    => $this->address_id,

            'address_full' => $this->address ? implode(', ', array_filter([
                $this->address->address,
                $this->address->number ? "nº {$this->address->number}" : null,
                $this->address->district,
                $this->address->city ? "{$this->address->city->name}/{$this->address->state?->code}" : null,
            ])) : null,

            'address'                     => new AddressResource($this->whenLoaded('address')),
            'date'                        => $this->date?->format('Y-m-d'),
            'period_type'                 => $this->period_type,
            'schedule_type'               => $this->schedule_type,
            'start_time'                  => $this->start_time,
            'end_time'                    => $this->end_time,
            'offers_meal'                 => $this->offers_meal,
            'status'                      => $this->status,
            'total_amount'                => $this->total_amount,
            'code'                        => $this->code,
            'code_verified'               => $this->code_verified,
            'service_package_id'          => $servicePackageId,
            'service_package_items_count' => $servicePackageItemsCount,
            'created_at'                  => $this->created_at?->toISOString(),
            'updated_at'                  => $this->updated_at?->toISOString(),
            'deleted_at'                  => $this->deleted_at?->toISOString(),
        ];
    }
}
