<?php

namespace App\Http\Resources\Option;

use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class Option extends JsonResource
{
    public $custom_fields = [];

    public function __construct($resource, $custom_fields = [])
    {
        $this->custom_fields = $custom_fields;

        parent::__construct($resource);
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $pnl = 0;

        $periodText = config('app.options_types');

        $diffSeconds = 0;

        if($this->status == 'active') {

            $createdTime = Carbon::parse($this->created_at)->getTimestamp();
            $targetTime = $createdTime + $periodText[$this->period];

            $diffSeconds =  $targetTime - time();

            if($diffSeconds < 0) {
                $diffSeconds = 0;
            }

        }


        if($this->status == "won") $pnl = $this->pnl;
        if($this->status == "lost") $pnl = $this->amount;

        $order = [
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'market' => $this->market->name,
            'symbol' => $this->currency->symbol,
            'amount' => $this->amount,
            'price' => $this->price,
            'market_price' => $this->market_price,
            'type' => $this->type,
            'period' => $this->period,
            'remaining' => $diffSeconds,
            'period_text' => $periodText[$this->period],
            'status' => $this->status,
            'pnl' => $pnl,
            'id' => $this->uuid,
        ];

        return $order;
    }
}
