<?php

require_once 'Upgrade.php';

use ComPixelCMS\MenuItem;
use ComPixelCMS\Upgrade;

class upgrade_2_18_1 extends Upgrade
{
    public function run()
    {
        $app = JFactory::getApplication();
        $globalParams = $this->getParams();

        $api_token = $app->get('pixel_cms_token');

        // Setting Globalparams
        if ($api_token) {
            $globalParams->set('pixel_cms_token', $api_token);
            $this->msg("Api Token in Globale Konfiguration geschrieben: $api_token.", 'notice');
        }
        $globalParams->set('pixel_cms_url', 'https://cms.pixel-kraft.de');
        $this->msg("PixelCMS Url gesetzt.", 'notice');
        $globalParams->set('pixel_cms_version', 'v1');
        $this->msg("PixelCMS Version gesetzt.", 'notice');
        $globalParams->set('cache', true);
        $this->msg("PixelCMS Cache aktiviert.", 'notice');
        $globalParams->set('pixel_cms_alias', '');
        $this->msg("PixelCMS Alias entfernt.", 'notice');

        if($traktorpool = $this->getTraktorpoolSettings()) {
            $globalParams->set('tracktorpool_username', 'pixel-kraft');
            $globalParams->set('tracktorpool_password', 'VG9gZ9au');
            if ($traktorpool['tracktorpool_apikey']) $globalParams->set('tracktorpool_apikey', $traktorpool['tracktorpool_apikey']);
            if ($traktorpool['tracktorpool_customer_id']) $globalParams->set('tracktorpool_customer_id', $traktorpool['tracktorpool_customer_id']);
            if ($traktorpool['tracktorpool_alias']) $globalParams->set('tracktorpool_alias', $traktorpool['tracktorpool_alias']);
            $this->msg("Globale Traktorpool konfiguration gesetzt.", 'notice');

            $this->unsetTraktorpoolSettings();
        } else {
            $this->msg("Traktorpool Konfiguration nicht aktualisiert.", 'error');
        }

        if ($this->saveParams()) {
            $this->msg("Gloable Konfiguration gespeichert");
        } else {
            $this->msg("Fehler beim Speichern der konfiguration", 'error');
        }
    }

    private function unsetTraktorpoolSettings()
    {
        $this->getMenuItems()->setLink([
            'tracktorpool_apikey' => null,
            'tracktorpool_customer_id' => null,
            'tracktorpool_alias' => null,
        ], [
            'view' => 'tracktorpool_products',
        ])->save();
    }

    private function getTraktorpoolSettings()
    {
        $menuItems = $this->getMenuItemsFiltered([
            'view' => 'tracktorpool_products',
        ]);

        /** @var MenuItem $link */
        if ($link = array_pop($menuItems)) {
            return $link->link;
        }
        return false;
    }
}
