<?php

namespace YSquare\GiftCert\Core;

use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\DatabaseProvider;
use OxidEsales\Eshop\Core\DbMetaDataHandler;
use OxidEsales\Eshop\Core\Module\Module;

/**
 * Class defines what module does on Shop events.
 */
class Events
{

    /**
     * Add missing tables if not already existent
     */
    public static function addMissingTablesOnUpdate()
    {
        $oDbMetaDataHandler = oxNew(DbMetaDataHandler::class);

        if (!$oDbMetaDataHandler->tableExists("ysgiftcert")) {
            DatabaseProvider::getDb()->execute(
                "CREATE TABLE `ysgiftcert` (
                    `OXID` char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'Gift certificate id',
                    PRIMARY KEY (`OXID`)
                  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
            );
        }

        if (!$oDbMetaDataHandler->tableExists("ysgiftcertlog")) {
            DatabaseProvider::getDb()->execute(
                "CREATE TABLE `ysgiftcertlog` (
                    `OXID` char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'Gift certificate log entry id',
                    PRIMARY KEY (`OXID`)
                  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
            );
        }
    }

    /**
     * Add missing field if it activates on old DB
     */
    public static function addMissingFieldsOnUpdate()
    {
        $oDbMetaDataHandler = oxNew(DbMetaDataHandler::class);


        /*
         * Extending Articles Table
         */
        $aTableFields = array(
            0 => array(
                'table'     => "oxarticles",
                'fieldname' => "YS_GIFTCERT",
                'fieldtype' => "tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Gift certificate article'",
            ),
            1 => array(
                'table'     => "oxarticles",
                'fieldname' => "YS_GIFTCERT_OFFLINE",
                'fieldtype' => "tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Gift certificate should be handled offline'",
            ),
            2 => array(
                'table'     => "oxarticles",
                'fieldname' => "YS_GIFTCERT_IMAGE",
                'fieldtype' => "varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Gift card image for the pdf file'",
            ),
            3 => array(
                'table'     => "oxarticles",
                'fieldname' => "YS_GIFTCERT_BUSINESS",
                'fieldtype' => "tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Gift certificate should be handled as business purchase'",
            ),
        );
        self::executeTableFieldAddition($aTableFields);

        /*
         * Extending Articles Table
         */
        $aTableFields = array(
            0 => array(
                'table'     => "oxorderarticles",
                'fieldname' => "YS_GIFTCERT",
                'fieldtype' => "tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Gift certificate article'",
            ),
        );
        self::executeTableFieldAddition($aTableFields);


        /*
         * Adding Fields to the new table ysgiftcert
         */
        $aTableFields = array(
            0 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSGIFTCERTNR",
                'fieldtype' => "varchar(255) NOT NULL DEFAULT '' COMMENT 'Coupon number'",
            ),
            1 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSINITIALDISCOUNT",
                'fieldtype' => "float(9,2) DEFAULT NULL COMMENT 'Initial value of the coupon'",
            ),
            2 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSRESTDISCOUNT",
                'fieldtype' => "float(9,2) DEFAULT NULL COMMENT 'Rest value of the coupon (if discount was used)'",
            ),
            3 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSRESERVED",
                'fieldtype' => "int(11) NOT NULL DEFAULT '0' COMMENT 'Time, when coupon is added to basket'",
            ),
            4 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSTIMESTAMP",
                'fieldtype' => "timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Timestamp'",
            ),
            5 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSDATEPURCHASED",
                'fieldtype' => "datetime DEFAULT NULL COMMENT 'Date of purchase'",
            ),
            6 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSDELIVERYOPTION",
                'fieldtype' => "tinyint NOT NULL DEFAULT 0 COMMENT 'How should the card be delivered? 0-email, 1-offline'",
            ),
            7 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSDELIVERYDATE",
                'fieldtype' => "date DEFAULT NULL COMMENT 'What date should the card be delivered?'",
            ),
            8 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSDELIVERED",
                'fieldtype' => "tinyint NOT NULL DEFAULT 0 COMMENT 'Has the card already be delivered?'",
            ),
            9 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "YSINDIVIDUALOPTIONS",
                'fieldtype' => "text NOT NULL DEFAULT '' COMMENT 'Options that are used for personalization in json format'",
            ),
            10 => array(
                'table'     => "ysgiftcert",
                'fieldname' => "OXORDERID",
                'fieldtype' => "CHAR(32) NOT NULL DEFAULT '' COMMENT 'Related OXID Order'",
            ),
        );
        self::executeTableFieldAddition($aTableFields);

        /*
         * Adding Fields to the new table ysgiftcertlog
         */
        $aTableFields = array(
            0 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSGIFTCERTID",
                'fieldtype' => "char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'Gift certificate id'",
            ),
            1 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSPOOLREDEEM",
                'fieldtype' => "tinyint NOT NULL DEFAULT 0 COMMENT 'Amount taken from the money pool?'",
            ),
            2 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSAMOUNTUSED",
                'fieldtype' => "float(9,2) DEFAULT NULL COMMENT 'Used value of the coupon'",
            ),
            3 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSORDERID",
                'fieldtype' => "char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'id of the order the coupon was used for'",
            ),
            4 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSUSERID",
                'fieldtype' => "char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL COMMENT 'id of the user that used the coupon'",
            ),
            5 => array(
                'table'     => "ysgiftcertlog",
                'fieldname' => "YSDATEUSED",
                'fieldtype' => "datetime DEFAULT NULL COMMENT 'Date, when (part of) coupon was used (set on order complete)'",
            ),
        );
        self::executeTableFieldAddition($aTableFields);

        /*
         * Adding Fields to user table
         */
        $aTableFields = array(
            0 => array(
                'table'     => "oxuser",
                'fieldname' => "YS_GIFTCERT_POOL_AMOUNT",
                'fieldtype' => "float(9,2) DEFAULT NULL COMMENT 'Users rest value out of giftcert redeems'",
            ),
        );
        self::executeTableFieldAddition($aTableFields);
    }

    public static function executeTableFieldAddition($aFieldsToAdd)
    {

        $oDbMetaDataHandler = oxNew(DbMetaDataHandler::class);

        if (is_array($aFieldsToAdd) && is_array($aFieldsToAdd[0])) {

            // This case covers an array with several fields
            foreach ($aFieldsToAdd as $aField) {
                if (!$oDbMetaDataHandler->fieldExists($aField['fieldname'], $aField['table'])) {
                    DatabaseProvider::getDb()->execute(
                        "ALTER TABLE `" . $aField['table']
                        . "` ADD `" . $aField['fieldname'] . "` " . $aField['fieldtype'] . ";"
                    );
                }
            }
        } elseif (is_array($aFieldsToAdd) && isset($aFieldsToAdd['table'])) {

            // This case covers one field given alone
            if (!$oDbMetaDataHandler->fieldExists($aFieldsToAdd['fieldname'], $aFieldsToAdd['table'])) {
                DatabaseProvider::getDb()->execute(
                    "ALTER TABLE `" . $aFieldsToAdd['table']
                    . "` ADD `" . $aFieldsToAdd['fieldname'] . "` " . $aFieldsToAdd['fieldtype'] . ";"
                );
            }
        }
    }

    /**
     * Execute action on activate event
     */
    public static function onActivate()
    {
        self::addMissingTablesOnUpdate();
        self::addMissingFieldsOnUpdate();

        $oDbMetaDataHandler = oxNew(DbMetaDataHandler::class);
        $oDbMetaDataHandler->updateViews();

        self::clearTmp();
    }

    /**
     * Execute action on deactivate event
     *
     * @return null
     */
    public static function onDeactivate()
    {
        self::clearTmp();
    }

    public static function clearTmp($sClearFolderPath = '')
    {
        $sTempFolderPath = realpath(\OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('sCompileDir'));

        if (!empty($sClearFolderPath) and
            (strpos($sClearFolderPath, $sTempFolderPath) !== false) and
            is_dir($sClearFolderPath)
        ) {

            // User argument folder path to delete from
            $sFolderPath = $sClearFolderPath;
        } elseif (empty($sClearFolderPath)) {

            // Use temp folder path from settings
            $sFolderPath = $sTempFolderPath;
        } else {
            return false;
        }

        $hDir = opendir($sFolderPath);

        if (!empty($hDir)) {
            while (false !== ($sFileName = readdir($hDir))) {
                $sFilePath = $sFolderPath . '/' . $sFileName;

                if (!in_array($sFileName, array('.', '..', '.htaccess')) and is_file($sFilePath)) {

                    // Delete a file if it is allowed to delete
                    @unlink($sFilePath);
                } elseif ($sFileName == 'smarty' and is_dir($sFilePath)) {

                    // Recursive call to clear smarty folder
                    self::clearTmp($sFilePath);
                }
            }
        }

        return true;
    }
}
