<?php

namespace App\Listeners\PHPXPress;

use Illuminate\Support\Facades\Validator;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;

class HwplusInvoiceItems {

    public function handle($event) {
        throw new \Exception('should never be called');
    }

    public function calculateSum($model) {

        $editor = DotenvEditor::load(storage_path('app/settings.env'));
        if(!$model->_items_at_hwplus_invoices) throw new \Exception('invalid invoice');
        $model = \Runtime::make('hwplus_invoices')->with('_items')->findOrFail($model->_items_at_hwplus_invoices->getKey());

        $zsum = 0; $fk = 0; $zsumvat = 0; $fkvat = 0; $pos = 0; $vat=[];

        foreach($model->_items AS $row) {
            $pos = round((float) str_replace(',', '.', $row->netprice) * (float) str_replace(',', '.', $row->amount), 2);

            $zsum = $zsum + $pos;
            $vat[$row->vat][] = $pos;
        }


         if($model->_premium_charge) {

            if("%" == $model->_premium_charge->unit) {

                $pos = $zsum / 100 * $model->_premium_charge->value;
                $zsum = $zsum + $pos;


            } else {

                $pos = $model->_premium_charge->value;
                $zsum = $zsum + $pos;

            }

            $vat[$model->_premium_charge->_vat->rate] = $pos;

        }

        foreach($vat AS $index => $val) {
            $zsumvat += round(array_sum($val) /100 * (float) str_replace(',', '.', $index), 2);
        }

        $sum = $zsum + $zsumvat;

        $model->net = $zsum;
        $model->gross = $sum;
        $model->save();

    }


    public function created($event) {

        $model = $event->model;

        $this->calculateSum($model);

    }

    public function updated($event) {

        $model = $event->model;
        $this->calculateSum($model);

    }

    public function deleted($event) {

        $model = $event->model;
        $this->calculateSum($model);

    }
}


