HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/netwerkbrabant/netwerkbrabant.nl/app/KommaApp/Products/Kms/ProductController.php
<?php

namespace App\KommaApp\Products\Kms;

/**
 * @author      Komma <info@komma.pro>
 * @copyright   (c) 2012-2016, Komma
 */

use App\KommaApp\Forms\Models\Request;
use App\KommaApp\Kms\Core\SectionController;
use App\KommaApp\Kms\Core\Tree\TreeService;
use App\KommaApp\Products\Models\Product;
use App\KommaApp\WeFact\WeFactAPI;
use App\KommaApp\WeFact\WeFactService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class ProductController extends SectionController
{
    protected $slug = "products";
    protected $forModelName = Product::class;

    private $weFactAttributes = ['price_amount', 'wefact_name', 'wefact_description'];

    /**
     * Constructor
     * @param ProductSection $section
     */
    public function __construct(ProductSection $section)
    {
        parent::__construct($section);
    }

    /**
     * This method will validate and save the model
     * It is called on create form submit,
     * and it is called on the form edit.
     *
     * @param null|Model $model
     * @param bool $updateExistingModel If we are updating an model that exists (true) or a new one (false)
     * @return mixed
     * @throws \Exception
     */
    public function store($model = null, $updateExistingModel = false)
    {
        // Store the old we fact attributes
        $oldWeFactAttributes = [];
        $shouldUpdateWeFact = false;
        foreach ($this->weFactAttributes as $weFactAttribute) {
            if(isset($model->{$weFactAttribute})) $oldWeFactAttributes[$weFactAttribute] = $model->{$weFactAttribute};
            else $oldWeFactAttributes[$weFactAttribute] = null;
        }

        //Create a root model if the forModelName instance implements the treeInterface
        $this->createRootTreeModelIfNeeded();

        $model = $this->section->setOrCreateModel($model);

        $this->section->generateAttributesAndAddThemToTabs();

        //Validate the form data
        $validator = $this->section->validateInputAndReturnValidator();

        //Check if the validator fails
        if ($validator->fails()) {

            //It fails, redirect back with errors
            return \Redirect::back()->withInput()->withErrors($validator->messages());

        }

        $model = $this->section->save($model);

        foreach ($this->weFactAttributes as $weFactAttribute){
            if($oldWeFactAttributes[$weFactAttribute] != $model->{$weFactAttribute}) $shouldUpdateWeFact = true;
        }

//        Log::info(self::class.': Store function. Is an ajax request: ' . \request()->ajax());

        if($shouldUpdateWeFact){

            /** @var WeFactService $weFactService */
            $weFactService = app()->make(WeFactService::class);

            $taxPercentage = $model->vat_amount;
            $productInput = [
                'ProductName' => $model->wefact_name,
                'ProductKeyPhrase' => $model->wefact_description,
                'PriceExcl' => WeFactAPI::convertPriceInclToExcl($model->price_amount, $taxPercentage),
                'TaxCode' => 'V' . $taxPercentage,
            ];

            // Get the WeFact Product
            $weFactSearchProduct = $weFactService->searchProductByName($model->wefact_name);

            if(empty($model->wefact_code)) {

                if($weFactSearchProduct->results == 0) {
                    Log::info(self::class.': Created Product' . $model->id);
                    $response = $weFactService->addProduct($productInput, 5);
                    $model->wefact_code = $response->ProductCode;
                }
                else {
                    Log::info(self::class.': Product with given name "' . $model->id . '" already found. Therefor created skipped. This is probably because of a bug in KMS that will trigger the store twice.');
                }
            }
            else{
                Log::info(self::class.': Edit product ' . $model->wefact_code);
                $response = $weFactService->editProduct($model->wefact_code, $productInput);
            }

            $model->wefact_modified_at = Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $response->Modified);
            $model->save();
        }

        //Set the siteSlug variable for routes that need the siteSlug variable in their route
        $routeParameters = [];
        $site = $this->siteService->getCurrentSite();
        if($site->exists)
            $routeParameters['siteSlug'] = $site->slug;
        $routeParameters[$this->slug] = $model;

        $sessionData = [
            'tabslug' => \Input::get('tabslug'),
            'success' => __('kms/global.saved')
        ];

        return \Redirect::action('\\'.get_class($this) . '@show', $routeParameters)->with($sessionData);
    }
}