<?php
class Shopware_Plugins_Backend_SITSCreditpass_Bootstrap extends Shopware_Components_Plugin_Bootstrap {

    /**
     * Install method of the plugin. Register the migration controller, create the backend menu item.
     * @return bool
     */
    public function install() {

    // Subscripte events
        $this->subscribeEvent(
            'Enlight_Controller_Dispatcher_ControllerPath_Backend_SITSCreditpass',
            'onGetControllerPath'
        );
        $this->subscribeEvent(
            'Enlight_Controller_Action_PreDispatch_Frontend_Checkout',
            'onPreDispatchCheckout'
        );
        $this->subscribeEvent(
            'Enlight_Controller_Action_PostDispatch_Frontend_Checkout',
            'onPostDispatchCheckout'
        );

        // Menu item
        $this->subscribeEvent(
            'Enlight_Controller_Action_PostDispatch_Backend_Index',
            'onPostDispatchBackendIndex'
        );

        // Create menu
        $parent = $this->Menu()->findOneBy(['id' => 23]);
        $item = $this->createMenuItem(array(
            'label' => 'SIT-Creditpass',
            'controller' => 'SITSCreditpass',
            'class' => 'sit-icon',
            'action' => 'index',
            'active' => 1,
            'parent' => $parent
        ));
        //$this->Menu()->addItem($item);
        //$this->Menu()->save();

        // Reset cache
        return array(
            'success' => true,
            'invalidateCache' => array('backend')
        );
    }

    /**
     * Method that return availability capabilities
     * @return array
     */
    public function getCapabilities(){
        return array(
            'install'=> true,
            'enable' => true,
            'delete' => true
        );
    }

    /**
     * Add backend css
     */
    public function onPostDispatchBackendIndex(Enlight_Event_EventArgs $args) {

        $request = $args->getSubject()->Request();
        $response = $args->getSubject()->Response();
        $view = $args->getSubject()->View();
        $args->getSubject()->View()->addTemplateDir($this->Path() . 'Views/');

        //CSS und Javascript laden
        $view->extendsTemplate('backend/menu/index.tpl');
    }

    /**
     * Backend controller path event. Returns the path of the backend migration controller.
     * @static
     * @param Enlight_Event_EventArgs $args
     * @return string
     */
    public function onGetControllerPath(Enlight_Event_EventArgs $args) {

        $controllerPath = $this->Path() . "Controllers/Backend/SITSCreditpass.php";
        return $controllerPath;
    }

    /**
     * Event listener function which called over the Enlight_Controller_Action_PreDispatch_Frontend_Checkout event.
     * The event fired when the customer is about to finish his checkout, before the actual dispatch.
     *
     * @param Enlight_Event_EventArgs $arguments
     */
    public function onPreDispatchCheckout(Enlight_Event_EventArgs $arguments) {

        /**@var $subject Shopware_Controllers_Frontend_Checkout */
        $subject = $arguments->getSubject();
        $request  = $subject->Request();
        $response = $subject->Response();
        $action = $request->getActionName();
        $view = $subject->View();

        if (!$request->isDispatched() || $response->isException() || !$view->hasTemplate()) {
            return;
        }

// echo "<br>onPreDispatchCheckout";				
// echo "<br>subject: " . $subject;		
// echo "<br>request: " . $request;	
// echo "<br>response: " . $response;	
// echo "<br>action: " . $action;	
// echo "<br>view: " . $view;

        $customerId = Shopware()->Session()->sUserId;
        if ($action !== "finish" || $customerId === null) {
            return;
        }

        // Get customer by Id
        /** @var $customer \Shopware\Models\Customer\Customer */
        $customer = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $customerId);
        if (!$customer) {
            return;
        }

        $includePath = dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))) . "/SITModuleFramework/modules/SITCreditpass/SITCreditpassConfigurator.php";
        if ( ! file_exists($includePath) ) {

            $includePath = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/SITModuleFramework/modules/SITCreditpass/SITCreditpassConfigurator.php";
            if ( ! file_exists($includePath) ) {
                return;
            }
        }

        // Get basket
        $basket = Shopware()->Modules()->Basket()->sGetBasket();

// echo "<pre>basket: " . $basket["Amount"] . "<br>";
// 	print_r($basket);
// echo "</pre>";

        $shop = Shopware()->Shop()->getId();

// echo "<pre>shop:<br>"; 
// 	print_r($shop);
// echo "</pre>";

        // Create article id
        $articleIdArray = array();
        foreach ($basket["content"] as $key => $content) {

            $articleIdArray[] = $content["articleID"];
        }

        // Get debit data
        $bankcode = "";
        $bankaccountnumber = "";
        $bankaccountiban = "";
        if ( method_exists($customer, "getDebit") ) {

            $debit = $customer->getDebit();

// echo "<br>load data by customer->getDebit():<pre>";
// print_r($debit);
// echo "</pre>";

// exit(0);

            if ($debit) {
                $bankcode = $debit->getBankCode();
                $bankaccountnumber = $debit->getAccount();
                $bankaccountiban = "";
            }
        }
        else if ( method_exists($customer, "getPaymentData") ) {

// echo "<br>load data by customer->getPaymentData()";

            foreach ($customer->getPaymentData() as $paymentData) {

                if ( get_class($paymentData) != "Shopware\Models\Customer\PaymentData" ) {
                    continue;
                }

                $bankaccountiban 		= $paymentData->getIban();
                if ( empty($bankaccountiban) ) {
                    $bankcode 			= $paymentData->getBankCode();
                    $bankaccountnumber 	= $paymentData->getAccountNumber();
                }
            }
        }

        //  Fill request array
        $requestArray = array(
            "request" 			=> "sit_creditpass_check_silent",
            "paymentid" 		=> $customer->getPaymentId(),
            "userid" 			=> $customerId,
            "shopid" 			=> $shop,
            "articleIdArray" 	=> $articleIdArray,
            "bankaccount" 		=> $bankcode,
            "bankaccountnumber" => $bankaccountnumber,
            "bankaccountiban"   => $bankaccountiban,
            "creditcardtype" 	=> "",
            "creditcardnumber"  => "",
            "amount"			=> str_replace(",", ".", $basket["Amount"]),
        );

// echo "<pre>request:<br>";
// 	$this->printArray($requestArray);
// echo "</pre>";

// 		exit(0);

        include_once($includePath);
        $SITCreditpassConfigurator = new SITCreditpassConfigurator();
        $returnArray = $SITCreditpassConfigurator->handleRequest($requestArray);

        if ( $returnArray["license"] == "missing" ){
            return;
        }

        if ( $returnArray["success"] != 1 ) {

            $errorMessage = Shopware()->Snippets()->getNamespace('frontend/plugins/sit_creditpass/translations')->get('messageCheckNegative');

            if ( empty($errorMessage) ) {
                $errorMessage = $this->encodeToUtf8($returnArray["message"]);
            }

            $subject->forward(
                'shippingPayment', 'checkout', 'frontend',  array("sitError"=>$errorMessage)
            );
        }
    }

    public function encodeToUtf8($string) {
        return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
    }

    /**
     * Event listener function which called over the Enlight_Controller_Action_PostDispatch_Frontend_Checkout event.
     * The event fired when the customer is about to finish his checkout, after the actual dispatch.
     *
     * @param Enlight_Event_EventArgs $arguments
     */
    public function onPostDispatchCheckout(Enlight_Event_EventArgs $arguments) {

        /**@var $subject Shopware_Controllers_Frontend_Checkout */
        $subject 	= $arguments->getSubject();
        $request  	= $subject->Request();
        $response 	= $subject->Response();
        $action 	= $request->getActionName();
        $view 		= $subject->View();

// echo "<br>onPostDispatchCheckout";
// echo "<br>subject: " . $subject;
// echo "<br>request: " . $request;
// echo "<br>response: " . $response;
// echo "<br>action: " . $action;
// echo "<br>view: " . $view;

        // Check available payments
        if ($action == "shippingPayment") {

            $includePath = dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))) . "/SITModuleFramework/modules/SITCreditpass/SITCreditpassConfigurator.php";
            if ( ! file_exists($includePath) ) {

                $includePath = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/SITModuleFramework/modules/SITCreditpass/SITCreditpassConfigurator.php";
                if ( ! file_exists($includePath) ) {
                    return;
                }
            }

            $customerId = Shopware()->Session()->sUserId;
            $shop = Shopware()->Shop()->getId();

            //  Fill request array
            $requestArray = array(
                "request" 			=> "sit_creditpass_check_negative_results",
                "userid" 			=> $customerId,
                "shopId" 			=> $shop
            );

            include_once($includePath);
            $SITCreditpassConfigurator = new SITCreditpassConfigurator();
            $returnArray = $SITCreditpassConfigurator->handleRequest($requestArray);

// 			echo "<pre>";
// 				print_r($view->sPayments);
// 			echo "</pre>";

            $newPayments = array();
            foreach ($view->sPayments as $key => $currentPayment) {

                // echo "check: " . $currentPayment["name"];
                if (
                    empty($returnArray)
                    || array_key_exists($currentPayment["id"], $returnArray["securePayments"] )
                ) {
                    $newPayments[] = $currentPayment;
                }
            }

            $view->sPayments = $newPayments;
        }

        // Check if the param sCpInfo was set by our preDispatch method.
        // If this is the case, set sBasketInfo
        if ($request->has('sitError')) {
// echo "<br>error: " . $request->getParam('sitError');
            $view->assign('sBasketInfo', $request->getParam('sitError'));
            $view->assign('sErrorMessages', array( $request->getParam('sitError') ) );
        }

        if (
            $action !== 'confirm'
            || !$request->isDispatched()
            || $response->isException()
            || !$view->hasTemplate()
        ) {
            return;
        }
    }

    /**
     * Returns the meta information about the plugin
     * as an array.
     * Keep in mind that the plugin description located
     * in the info.txt.
     *
     * @return array
     */
    public function getInfo() {

        return array(
            'version' => $this->getVersion(),
            'label'   => $this->getLabel(),
            'author' => '<a href="https://www.shopmodul24.de">Schwinkendorf Service GmbH</a>',
            'description' => file_get_contents( dirname(__FILE__) . '/info.txt'),
            'support' => 'https://www.shopmodul24.de',
            'changes' =>array(
                '2.0.1'=>array(
                    'releasedate' => '2016-02-11',
                    'lines' => array('Update for Shopware 5')
                ),
                '2.0.2'=>array(
                    'releasedate' => '2016-09-01',
                    'lines' => array('Update for Shopware 5.2')
                ),
                '2.0.3'=>array(
                    'releasedate' => '2016-09-08',
                    'lines' => array('Hide all unsecure payments on existing negative checks')
                ),
                '2.0.4'=>array(
                    'releasedate' => '2017-01-12',
                    'lines' => array('Individual user and password for each check possible')
                ),
                '2.0.5'=>array(
                    'releasedate' => '2017-05-05',
                    'lines' => array('Update for PHP 7')
                ),
                '2.0.6'=>array(
                    'releasedate' => '2017-11-30',
                    'lines' => array('Update for PHP 7.1 - Whitelist Groups')
                ),
                '2.0.7'=>array(
                    'releasedate' => '2018-05-21',
                    'lines' => array('DSGVO Update')
                ),
                '2.0.8'=>array(
                    'releasedate' => '2020-06-10',
                    'lines' => array('Update for latest Shopware 5 and composer created shops')
                )
            ),
            'revision' => '1'
        );
    }

    /**
     * Returns the version of the plugin as a string
     *
     * @return string
     */
    public function getVersion() {
        return '2.0.13';
    }

    /**
     * Returns the well-formatted name of the plugin
     * as a sting
     *
     * @return string
     */
    public function getLabel() {
        return 'SIT-Creditpass';
    }

    public function printArray($array) {

        echo "<pre>";

        foreach ($array as $key => $value) {

            echo $key . " => " . $value . "  ";
        }

        echo "</pre>";
    }
}