<?php
/*
 * 888888ba                 dP  .88888.                    dP
 * 88    `8b                88 d8'   `88                   88
 * 88aaaa8P' .d8888b. .d888b88 88        .d8888b. .d8888b. 88  .dP  .d8888b.
 * 88   `8b. 88ooood8 88'  `88 88   YP88 88ooood8 88'  `"" 88888"   88'  `88
 * 88     88 88.  ... 88.  .88 Y8.   .88 88.  ... 88.  ... 88  `8b. 88.  .88
 * dP     dP `88888P' `88888P8  `88888'  `88888P' `88888P' dP   `YP `88888P'
 *
 *                          m a g n a l i s t e r
 *                                      boost your Online-Shop
 *
 * -----------------------------------------------------------------------------
 * (c) 2010 - 2021 RedGecko GmbH -- http://www.redgecko.de
 *     Released under the MIT License (Expat)
 * -----------------------------------------------------------------------------
 */

/**
 * magnalister Plugin
 * Active magnalister Plugin in Shopware
 */
class Shopware_Plugins_Backend_RedMagnalister_Bootstrap extends Shopware_Components_Plugin_Bootstrap {

    /**
     * Plugin install method
     *
     * @return array|bool success
     */
    public function install() {
        $update = $this->update('');
        if( $update === true){
            $this->subscribeEvent('Enlight_Controller_Dispatcher_ControllerPath_Backend_Magnalister', 'onGetMagnalister');
            $this->subscribeEvent('Enlight_Controller_Dispatcher_ControllerPath_Frontend_Magnalister', 'onGetMagnalisterDo');
            $this->subscribeEvent('Enlight_Controller_Action_PostDispatch_Backend_Order', 'onBackendMagnalisterOrderPostDispatch');
            $this->subscribeEvent('Enlight_Controller_Front_RouteShutdown', 'onRouteShutdown');

            $logoURL = '../engine/Shopware/Plugins/Community/Backend/RedMagnalister/plugin.png';
            $this->createMenuItem(array(
                'label' => 'magnalister',
                'controller' => 'Magnalister',
                'class' => '\" style=\"background: url(' . $logoURL . ') no-repeat scroll 0 0 transparent !important;',
                'action' => 'Index',
                'active' => 1,
                'parent' => $this->Menu()->findOneBy(array('id' => 30)),
            ));
            return array('success' => true);
        }
        return $update;
    }

    /**
     * Enable plugin method
     *
     * @return bool|array
     */
    public function uninstall()
    {
        return array('success' => true, 'invalidateCache' => array('backend'));
    }

    /**
     * Plugin update method
     * It force plugin to go through magnalister installation after each update or installation in Shopware Plugin Manager
     * @return bool success
     */
    public function update($oldVersion) {
        //deleting magnalister cache
        $sCachePath = __DIR__.DIRECTORY_SEPARATOR.'writable'.DIRECTORY_SEPARATOR.'cache';
        if(is_dir($sCachePath)) {
            $files = glob($sCachePath.'/*');
            foreach($files as $file) {
                if (file_exists($file) && !is_dir($file)) {
                    unlink($file);
                }
            }
        }
        try {
            $connection = $this->get('dbal_connection');
            $connection->delete('magnalister_config', array('mpID' => '0', 'mkey'=>'after-update'));
        } catch(\Exception $ex) {
        }
        return true;//by downloading package from community store it is not needed to force to start magnalister installation process
    }

    /**
     * Enable plugin method
     *
     * @return bool|array
     */
    public function enable()
    {
        return array('success' => true, 'invalidateCache' => array('backend'));
    }

    /**
     * Disable plugin method
     *
     * @return bool|array
     */
    public function disable()
    {
        return array('success' => true, 'invalidateCache' => array('backend'));
    }

    /**
     * Registers the magnalister plugin in order to bypass the service mode for the magnalister frontend controller.
     * This makes sure all external magnalister crons are allowed to run (far away...).
     *
     * @param Enlight_Controller_EventArgs $args
     *
     * @return void
     */
    public function onRouteShutdown(Enlight_Controller_EventArgs $args) {
        $request = $args->getRequest();
        if (($request->getPathInfo() == '/Magnalister/index') && ($request->getControllerName() == 'error')) {
            // Set the controller name back to magnalister and set it to dispatched.
            // @see Shopware_Plugins_Core_Router_Bootstrap::initServiceMode()
            $request->setControllerName('Magnalister')->setActionName('index')->setDispatched(true);
        }
    }

    /**
     * Registers the magnalister plugin in the order view to show additional marketplace specific
     *  information for each imported order.
     * @return void
     */
    public function onBackendMagnalisterOrderPostDispatch(Enlight_Event_EventArgs $args) {
        $view = $args->getSubject()->View();
        /* @var $view Enlight_View_Default */
        $aCurrentData = $view->getAssign('data');
        $blCheck = true;//check if the data related to order model or not
        foreach (array(
                     'number',
                     'status',
                     'dispatchId',
                     'cleared'
                 ) as $sValue) {
            if (!isset($aCurrentData[0]) || !array_key_exists($sValue, $aCurrentData[0])) {
                $blCheck = false;
            }
        }
        if ($blCheck) {
            $_PluginPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Lib' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'ML.php';
            if (!file_exists($_PluginPath) && file_exists(dirname(__FILE__).'/../../../../../../../../magnalister/Core/ML.php')) {
                $_PluginPath = dirname(__FILE__).'/../../../../../../../../magnalister/Core/ML.php';
            }
            require_once($_PluginPath);

            if (ML::isInstalled()) {
                ML::setFastLoad(true);
                foreach ($aCurrentData as &$aRow) {
                    $oOrder = MLOrder::factory()->set('current_orders_id', $aRow['id']);
                    $sLogo = $oOrder->getLogo();
                    $aRow['magnalisterlogo'] = $sLogo == ''? '' :'<img src="'.$sLogo.'" />';
                }
                $view->clearAssign('data');
                $view->assign(array('data'=>$aCurrentData));
            }
        }

        // Add template directory
        $args->getSubject()->View()->addTemplateDir(
            $this->Path() . 'Views/'
        );

        if ($args->getRequest()->getActionName() === 'index') {
            $view->extendsTemplate(
                'backend/order/order_magnalister_app.js'
            );
        }
        if ($args->getRequest()->getActionName() === 'load') {
            $view->extendsTemplate(
                'backend/order/view/detail/customer_preferences/window.js'
            );
            $view->extendsTemplate(
                'backend/order/view/magnalister/list/list.js'
            );
            $view->extendsTemplate(
                'backend/order/model/magnalister_order.js'
            );
        }

    }

    /**
     * Just points to the path of this controller.
     *
     * @static
     * @param Enlight_Event_EventArgs $args
     * @return string
     */
    public function onGetMagnalister(Enlight_Event_EventArgs $args) {
        $this->setShopwareVersionForMagnalister();
        $this->Application()->Template()->addTemplateDir(
            $this->Path() . 'Views/', 'magnalister'
        );
        return $this->Path() . 'Controllers/Backend/Magnalister.php';
    }

    /**
     * Just points to the path of this controller.
     *
     * @static
     * @param Enlight_Event_EventArgs $args
     * @return string
     */
    public function onGetMagnalisterDo(Enlight_Event_EventArgs $args) {
        $this->setShopwareVersionForMagnalister();
        $this->Application()->Template()->addTemplateDir(
            $this->Path() . 'Views/', 'magnalister'
        );
        return $this->Path() . 'Controllers/Frontend/Magnalister.php';
    }

    /**
     * Get Infodata for Plugin-Manager
     * @return array
     */
    public function getInfo() {
        return array(
            'version' => $this->getVersion(),
            'autor' => 'RedGecko GmbH',
            'copyright' => 'Copyright &copy; 2010 - '.date('Y').', RedGecko GmbH',
            'label' => 'magnalister4Shopware',
            'source' => "Local",
            'description' => 'magnalister f&uuml;r Shopware',
            'license' => 'MIT',
            'support' => 'https://otrs.magnalister.com/otrs/public.pl',
            'link' => 'https://www.magnalister.com/'
        );
    }

    protected function setShopwareVersionForMagnalister(){
        if(!method_exists($this, 'assertMinimumVersion')){
            define('MLSHOPWARE_VERSION', 4);
        }elseif ($this->assertMinimumVersion('5')) {
            define('MLSHOPWARE_VERSION', 5);
        } else {
            define('MLSHOPWARE_VERSION', 4);
        }
    }

    /**
     * Get version tag of this plugin to display in manager
     * @return string
     */
    public function getVersion() {
        $oPluginData = simplexml_load_string(file_get_contents(dirname(__FILE__).'/plugin.xml'));
        if(!empty($oPluginData)) {
            define('MAGNALISTER_PLUGIN_VERSION', current($oPluginData->version));
            return MAGNALISTER_PLUGIN_VERSION;
        } else{
            return '';
        }
    }

}

if (file_exists(dirname(__FILE__).'/BootstrapLegacy.php')) {
    require_once(dirname(__FILE__).'/BootstrapLegacy.php');
}
