<?php

namespace App\Http\Resources;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Http\Resources\Json\JsonResource;
use Exception;

class MappableTransactionWithDetailsResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $data = [
            'status' => 'success',
            'id' => $this->id,
            'updated_at' => $this->updated_at,
            'type' => $this->type,
            'amount' => $this->amount,
            'debtor_code' => null,
            'order_reference' => null,
            'bill_no' => null,
            'marking' => null,
            'created_at' => null
        ];

        if ($this->type === TransactionType::PAYMENT) {
            $order = $this->owner->owner->owner;
            $data['order_reference'] = $order->reference;
            $data['debtor_code'] = $order->companyModule->company->debtor;
            $data['created_at'] = $this->owner->created_at; // invoice date
        } elseif (in_array($this->type, [TransactionType::GROUP_PAYMENT, TransactionType::TOP_UP])) {
            $connection = $this->owner->owner->inviters()->withPivot('invitee_reference')->first();
            $data['marking'] = $connection ? $connection->pivot->invitee_reference : '';
            $data['bill_no'] = $this->bill_no;
            $data['created_at'] = $this->created_at;
        } else {
            $payments = $this->transactions()
                ->payments()->where('status', ApprovalStatus::APPROVED)
                ->get();

            if ($payments->count()) {
                $data['payment_transactions'] = $payments->map(function ($payment) {
                    $order = $payment->owner->owner->owner;
                    return [
                        'id' => $payment->id,
                        'updated_at' => $payment->updated_at,
                        'debtor_code' => $order->companyModule->company->debtor,
                        'order_reference' => $order->reference,
                        'bill_no' => null,
                        'type' => $payment->type,
                        'marking' => null,
                        'amount' => $payment->amount,
                        'created_at' => $this->created_at
                    ];
                })->toArray();
            } else {
                $data['status'] = 'error';
                $data['amount'] = 'Transaction Type not allowed';
                $data['transaction_type'] = $this->type;
                $data['payment_transactions'] = null;
                $data['created_at'] = null;
            }
        }

        return $data;
    }
}
