<?php

namespace App\Http\Resources;

use ArrayObject;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;

class VoucherResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $filteredRedemptions = new ArrayObject([]);
        if ($request->has('filters') && (str_contains($request->input('filters'), "has_vouchers_all_with_user") )) {
            //|| str_contains($request->input('filters'), "has_vouchers_all_with_company")
            $filteredRedemptions = new ArrayObject([]);
        }
        else{
            $filteredRedemptions = $this->redemptions->filter(function ($redemption) {
                return $redemption->transaction && $redemption->transaction->owner;
            });
        }

        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'code' => $this->code,
            'type' => $this->type,
            'value' => (float) $this->value,
            'start_date' => $this->start_date,
            'end_date' => $this->end_date,
            'is_redeemed' => $filteredRedemptions->count() > 0,
            'email' => $this->email ? new KeyValueBasicResource($this->email->where('key', $this->code.'_EMAIL_COUNT')->first()) : null,
        ];
    }
}
