<?php

namespace App\Http\Resources\Opportunity;

use App\Enums\StagesOpportunity;
use Illuminate\Http\Resources\Json\ResourceCollection;

class KanbanOpportunityResource extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            [
                'title' => 'LEAD',
                'items' => $this->formatItems($this->filterByStage(StagesOpportunity::LEAD->value)),
            ],
            [
                'title' => 'PROSPECTO',
                'items' => $this->formatItems($this->filterByStage(StagesOpportunity::PROSPECT->value)),
            ],
            [
                'title' => 'PREVENTA',
                'items' => $this->formatItems($this->filterByStage(StagesOpportunity::PRESALE->value)),
            ],
            [
                'title' => 'VENTA',
                'items' => $this->formatItems($this->filterByStage(StagesOpportunity::SALE->value)),
            ],
            [
                'title' => 'ENTREGA',
                'items' => $this->formatItems($this->filterByStage(StagesOpportunity::DELIVERY->value)),
            ],
        ];
    }

    private function filterByStage($stage)
    {
        return $this->collection->filter(function ($opportunity) use ($stage) {
            return $opportunity->stage->title == $stage;
        });
    }
    private function formatItems($opportunities)
    {
        return $opportunities->map(function ($opportunity) {
            return [
                'id' => $opportunity->id,
                'project'=> $opportunity->property?->project?->title ?: null, // Uso de ?-> para prevenir el acceso a null
                'property' => $opportunity->property?->code ?: null,
                'property_type' => $opportunity->property?->property_type?:null,
                'price'=> $opportunity->property?->base_price ?: null,
                'customer_id'=>$opportunity->customer?->id ?: null,
                'name' => $opportunity->customer?->name ?: null,
                'phone'=> $opportunity->customer?->phone ?: null,
                'stage' => $opportunity->stage?->title ?: null,
                'user_id'=> $opportunity->user_id,
                'created_at'=> $opportunity->created_at,
                'inCharge'=> $opportunity->user?->name.' '. $opportunity->user?->last_name ?: null,
                'lastActivity' => new ActivityResource($opportunity->activities()->latest()->first()), // Asumiendo que aquí podrías tener lógica para las actividades
                'type_customer'=>  $opportunity->customer?->type_customer ?: null, // Asumiendo que es un valor fijo, puedes mantenerlo
                'cantComments'=> '1', // Asumiendo que es un valor fijo, puedes mantenerlo
            ];
        })->values()->toArray();
    }
}
