<?php

namespace Modules\Payment\Traits;
use Illuminate\Http\Request;
use Modules\Payment\Models\Payment;
use Modules\Main\Models\Complex;
trait Paymentable
{
    private $defaultValue = -1; // -1 || null
    protected static function boot()
    {
        parent::boot();

        static::created(function ($item)
        {

        });
    }

    private function getClassName()
    {
        $reflect = new \ReflectionClass($this);
        return $reflect->getShortName();
    }

    public function getPaymentable(Complex $complex)
    {
        $paymentable = Payment::where('paymentable_type', $this->getClassName())
            ->where('paymentable_id', $this->id)
            ->where('complex_id', $complex->id);
        switch ( $paymentable->count() )
        {
            case 0:
                return Payment::create([
                    'paymentable_type' => $this->getClassName(),
                    'paymentable_id'   => $this->id,
                    'complex_id'       => $complex->id,
                    'value'            => ($this->getClassName() == 'Company') ? null : -1
                ]);
            case 1:
                return $paymentable->first();
            default:
                abort(404);

        }
        return false;
    }


    public function setPayment(Complex $complex, $value)
    {
        $paymentable = $this->getPaymentable($complex);
        if ($value >= 0 && $value <= 100)
        {
            $paymentable->update([
                'value' => $value            //-1 значит, что значение наследуется от родительского
            ]);
            return true;
        }

        return false;
    }

    public function setAsParentPayment(Complex $complex)
    {
        $value = -1;
        if ($this->getClassName() == 'Agent')
        {
            $company = $this->company;
            $companyPayment = $company->getPaymentable($complex);
            if ($companyPayment->value === null || $companyPayment->value == -1)
            {
                $value = null;
            }
        }

        $paymentable = $this->getPaymentable($complex);
        $paymentable->update([
            'value' => $value           //-1 значит, что значение наследуется от родительского
        ]);
        return true;
    }

    public function unsetPayment(Complex $complex)
    {
        $paymentable = $this->getPaymentable($complex);
        $paymentable->update([
            'value' => null
        ]);
        return true;
    }
}
