<?php
/**
 * Main backend controller for magnalister. Initializes the magnalister app.
 */

include_once str_replace('\\', '/',dirname(__FILE__)).'/MagnalisterAbstract.php';
class Shopware_Controllers_Backend_Magnalister extends Shopware_Controllers_Magnalister_Backend_MagnalisterAbstract {

    /**
     * Disables output buffering in Enlight_Controller_Dispatcher_Default
     * @see Enlight_Controller_Dispatcher_Default
     * @return void
     */
    public function init() {
        // Disables output buffering
        $this->Front()->setParam('disableOutputBuffering', true);
        parent::init();
    }

    /**
     * Main entry point for the magnalister app that will be loaded
     * in an iframe in the backend.
     */
    public function appAction() {
        $appPath = dirname(dirname(str_replace(str_replace('\\', '/',Enlight_Application::Instance()->AppPath()), '', str_replace('\\', '/', dirname(__FILE__)))));
        $_PluginPath = Enlight_Application::Instance()->AppPath($appPath) . 'Lib/Core/ML.php';

        $sShopwareReversion = $this->container->get('config')->get('revision');

        define("MLSHOPWAREREVERSION", $this->container->get('config')->get('revision'));
        define("MLSHOPWAREVERSION", $this->container->get('config')->get('version'));

        $debugPrint = '';
        if (!file_exists($_PluginPath) && file_exists($appPath.'/Lib/Core/ML.php')) {
            $_PluginPath = $appPath. '/Lib/Core/ML.php';
        }
        if (!file_exists($_PluginPath)) {
            $_PluginPath = dirname(__FILE__).'/../../../../../../../../../../magnalister/Core/ML.php';
        }
        if (file_exists($_PluginPath)) {
            require_once($_PluginPath);

            //preset http response code to 200
            http_response_code(200);
            $output = ML::gi()->run();

            /* @var $sClientVersion string will be added to url as parameter to avoid browser-cache */
            $sClientVersion = MLSetting::gi()->get('sClientBuild');
            $MLcss = '';
            $MLjs = '';
            foreach (array_unique(MLSetting::gi()->get('aCss')) as $sFile) {//echo $sFile;
                $MLcss .= '
                    <link rel="stylesheet" type="text/css" href="' . sprintf(MLHttp::gi()->getResourceUrl('css_'.$sFile), $sClientVersion) . '">';
            }
            $sMainUrl = MLHttp::gi()->getBaseUrl();

            $MLjs .='
                <script type="text/javascript">
                    var shopware_version = "' . $sShopwareReversion . '/";
                </script>';

            foreach (array_unique(MLSetting::gi()->get('aJs')) as $sFile) {
                if (strpos($sFile, 'react') !== false) {

                    $MLjs .= '
<script defer="defer" src="' . sprintf(MLHttp::gi()->getResourceUrl('js_'.$sFile), $sClientVersion) . '">

</script>';
                } else {
                    $MLjs .= '
                    <script src="' . sprintf(MLHttp::gi()->getResourceUrl('js_' . $sFile), $sClientVersion) . '" type="text/javascript"></script>';
                }
            }

            $MLbodyClass = implode(' ', MLSetting::gi()->get('aBodyClasses'));
        } else {
            ob_start();
            var_dump($_PluginPath);
            $_path = ob_get_clean();
            $debugPrint .= trim($_path).' not found!' . "\n\n";
        }

        header('Content-Type: text/html; charset=utf-8');
        echo('<!DOCTYPE html>
            <html>
                <head>
                    <meta charset="utf-8">
                    <title>magnalister Admin</title>
                    <style>body { font: 12px/1.3em sans-serif; }</style>
                    '.$MLcss.'
                    '.$MLjs.'
                </head>
                <body class="'.$MLbodyClass.'">
                    '.$output.'
                    <pre>' . $debugPrint . '</pre> 
                </body>
            </html>
        ');
        \MagnalisterFunctions::stop();
    }

    /**
     * Enables the marketplace logo in the order overview.
     * @return void
     */
    public function isMagnalisterOrderAction() {
        $orderId = $this->Request()->getParam("orderId");
        try {
            $_PluginPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . 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()){
                throw new Exception('magnalister is not installed');
            }
            $hasTransactionId = Shopware()->Db()->fetchOne("SELECT COUNT(*) AS `count` FROM `magnalister_orders` WHERE `current_orders_id` = ? ", array($orderId));

            if (!empty($hasTransactionId)) {
                ML::setFastLoad(true);
                $oOrder = MLOrder::factory()->set('current_orders_id', $orderId);
                $sTitleHtml = $this->Request()->getParam('img') ? $oOrder->getLogo() : $oOrder->getTitle();
                $string = '';
                if ($oOrder->get('special') !== null) {
                    ob_start();
                    require(MLFilesystem::gi()->getViewPath('hook_orderdetails'));
                    $string = ob_get_clean();
                }

                $this->View()->assign(
                    array(
                        'success' => true,
                        'magnaorderdetailhtml' => $string ,
                        'logo' => $sTitleHtml ,
                    )
                );
            } else {
                $this->View()->assign(
                    array(
                        'success' => false
                    )
                );
            }
        } catch (Exception $oExc) {

            $this->View()->assign(
                array(
                    'success' => false
                )
            );
        }
    }

    /**
     * Main entry point for the magnalister app that will be loaded
     * in an iframe in the backend.
     */
    public function imageResizeAction() {
        try {
            $aMlGet = Shopware()->Front()->Request()->getQuery('ml');
            $this->resize($aMlGet['src'], $aMlGet['x'], $aMlGet['y'], $aMlGet['dst']);
            echo($aMlGet['dst']);
        } catch (Exception $exc) {
            echo '<pre>';
            echo $exc->getTraceAsString();
            echo($exc->getMessage());
            echo '</pre>';
        }
        \MagnalisterFunctions::stop();
    }

    /**
     * because of some cache problem in shopware,
     * when user try to see Order list in shopware backend ,
     * shopware try to call magnalister controller
     * so in this situation we try to redirect it to correct controller
     */
    public function getListAction(){
        $sCurrentUrl = str_replace('Magnalister', 'Order', $_SERVER['REQUEST_URI']);
        $this->redirect($sCurrentUrl);
    }

    /**
     * because of some cache problem in shopware,
     * when user try to save Order detail in shopware backend ,
     * shopware try to call magnalister controller
     * so in this situation we try to forward it to correct controller
     */
    public function __call($name, $value = null) {
        if ('Action' == substr($name, -6)) {
            $actionName = str_replace('Action','', $name);
            $response = $this->forward($actionName,'Order');
            return $response;
        }

        return parent::__call($name, $value);
    }

    /**
     * to resize images
     * @param type $sSrc
     * @param type $iMaxWidth
     * @param type $iMaxHeight
     * @param type $sDst
     * @param type $iCompression
     * @return boolean
     */
    protected function resize($sSrc, $iMaxWidth, $iMaxHeight, $sDst, $iCompression=80){
        if (file_exists($sDst)) {
            unlink($sDst);
        }
        $src = array();
        $dst = array();
        $dimensions = getimagesize($sSrc);
        if (is_array($dimensions)) {
            $src['w'] = $dimensions[0];
            $src['h'] = $dimensions[1];
            $src['type'] = $dimensions[2];
            if ($iMaxWidth == '0') {
                $iMaxWidth = ($src['w'] / ($src['h'] / $iMaxHeight));
            }

            $thiso = ($src['w'] / $iMaxWidth);
            $thisp = ($src['h'] / $iMaxHeight);
            $dst['w'] = ($thiso > $thisp) ? $iMaxWidth : round($src['w'] / $thisp); // width
            $dst['h'] = ($thiso > $thisp) ? round($src['h'] / $thiso) : $iMaxHeight; // height
            if($src['w'] < $dst['w'] || $src['h'] < $dst['h']){
                //we don't increase size of image, that will damage resolution
                $iImageType = function_exists('exif_imagetype')? exif_imagetype($sSrc) : $src[2];//that could be possible, that exif_imagetype is not existed in PHP or was not configured
                if($iImageType == IMAGETYPE_PNG){
                    $dst['w'] = $src['w'] ;
                    $dst['h'] = $src['h'] ;
                }else{
                    return @copy($sSrc, $sDst);
                }
            }
        }
        $src['image'] = @imagecreatefromstring(@file_get_contents($sSrc));

        if (!is_resource($src['image'])) {
            unset($src);
            unset($dst);
            return false;
        }

        $success = true;
        if (function_exists('imagecreatetruecolor')) {
            $dst['image'] = imagecreatetruecolor($dst['w'], $dst['h']); // created thumbnail reference GD2
        } else {
            $dst['image'] = imagecreate($dst['w'], $dst['h']); // created thumbnail reference GD1
        }
        //use white background when png image has transparent background
        $white = imagecolorallocate($dst['image'], 255, 255, 255);
        imagefilledrectangle($dst['image'], 0, 0, $dst['w'], $dst['h'], $white);

        if (imagecopyresampled($dst['image'], $src['image'], 0, 0, 0, 0, $dst['w'], $dst['h'], $src['w'], $src['h'])) {
            $success = @imagejpeg($dst['image'], $sDst, $iCompression);
        } else {
            $success = false;
        }
        imagedestroy($src['image']);
        imagedestroy($dst['image']);

        unset($src);
        unset($dst);
        return $success;
    }
}
