<?php
namespace App\Services\Yard;

use App\Services\Util;
use Illuminate\Support\Collection;

class Margin
{
    public $items;
    public $commission;
    public $net_discount;
    public $net_partner_commission;
    public $net_price;
    public $net_amount;


    public function __construct()
    {
        $this->items = new Collection;
    }

    public function add($price_from, $values){
        $this->items->push(new MarginItems($price_from, $values));
    }

    public function setCommission(Commission $commission){
           $this->commission = $commission;
    }
    public function isMargin(){
        return count($this->items) ? true : false;
    }

    public function calculate(){

        if($this->commission){
            $this->net_discount += $this->commission->single_value_commission;
            $this->net_partner_commission += $this->commission->single_partner_commission;
            $this->net_amount +=  $this->commission->single_amount_commission;
            $this->net_price +=  $this->commission->single_price_net_commission;

        }

        if($this->isMargin()){
            foreach ($this->items as $item){
                $this->net_discount += $item->value_margin;
                $this->net_partner_commission += $item->value_commission;
                $this->net_amount += $item->new_price_net;
                $this->net_price +=  $item->new_price_net;
            }
        }

    }
    public function getFormatted($key)
    {
        return isset($this->{$key}) ? Util::formatNumber($this->{$key}) : "";
    }


    public function toArray()
    {
        return [
            'items' => $this->items,
            'commission' => $this->commission,
            'net_discount' => $this->net_discount,
            'net_partner_commission' => $this->net_partner_commission,
            'net_price' => $this->net_price,
            'net_amount' => $this->net_amount,
        ];
    }


    public function restore($content)
    {

        // Unserialize the content (either array if new, or collection if old)
        $storedContent = unserialize($content);

        if (is_array($storedContent)) {
            $this->fromArray($storedContent);
        }
        //TODO - check this
        // If the old approach and is Collection, push into existing items
       /* if ($storedContent instanceof Collection) {
            foreach ($storedContent as $item) {
                $this->items->put($item);
            }
        }*/

    }


    public function fromArray($array)
    {
        $this->items = $array['items'];
        $this->commission = $array['commission'];
        $this->net_discount = $array['net_discount'];
        $this->net_partner_commission = $array['net_partner_commission'];
        $this->net_price = $array['net_price'];
        $this->net_amount = $array['net_amount'];

        return $this;
    }

}