<?php

namespace App\Http\Resources;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Resources\Json\JsonResource;

class GroupResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {

        if(!$this->issuerCompany){
            dd($this->id);
        }
        return [
            'id' => $this->id,
            'original_amount' => (float) $this->original_amount,
            'original_currency' => new CurrencyResource($this->original_currency),
            'issuer_name' => $this->issuerCompany->name,
            'issuer_id' => $this->issuerCompany->id,
            'amount' => (float) $this->amount,
            'service_charge' => (float) $this->amount,
            'currency' => new CurrencyResource($this->currency),
            'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'),
            'currency_rate' => (float) $this->currency_rate,
            'transactions' => $this->transactions()->get()->pluck('owner.owner.marking'),
            'complete_transactions' => $this->transactions()->whereHasMorph('owner', [Transaction::class], function($query){
                return $query->whereHas('booking', function($query){
                    return $query->whereHas('transactions', function($query){
                        return $query->where('type', TransactionType::PURCHASE_ORDER)->where('status', '=', ApprovalStatus::APPROVED);
                    });
                });
            })->get()->pluck('owner.owner.marking'),
            'documents' => [
                'currency_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::CURRENCY_VENDOR_ORDER)->first()),
                'purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::BULK_PURCHASE_ORDER)->first())
            ]
        ];
    }
}
