<?php
/*
 * ----------------------------------------------------------------------
 *
 *                          Borlabs Cookie
 *                      developed by Borlabs
 *
 * ----------------------------------------------------------------------
 *
 * Copyright 2018 Borlabs - Benjamin A. Bornschein. All rights reserved.
 * This file may not be redistributed in whole or significant part.
 * Content of this file is protected by international copyright laws.
 *
 * ----------------- Borlabs Cookie IS NOT FREE SOFTWARE -----------------
 *
 * @copyright Borlabs - Benjamin A. Bornschein, https://borlabs.io
 * @author Benjamin A. Bornschein, Borlabs ben@borlabs.io
 *
 */

namespace BorlabsCookie\Cookie;

class Uninstall
{

    private static $instance;

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    public function __construct()
    {
    }

    /**
     * uninstallPlugin function.
     *
     * @access public
     * @return void
     */
    public function uninstallPlugin()
    {
        global $wpdb;

        // Remove cached files. This has to be executed before the tables are removed, otherwise we get an error due the code in __construct() of ContentBlocker
        $cacheFolder = Frontend\ContentBlocker::getInstance()->getCacheFolder();

        $this->deleteFilesInDirectory($cacheFolder);

        if ($this->isDirectoryEmpty($cacheFolder)) {
            rmdir($cacheFolder);
        }

        if (is_multisite()) {
            $allBlogs = $wpdb->get_results('
                SELECT
                    `blog_id`
                FROM
                    `'.$wpdb->prefix.'blogs`
            ');

            if (!empty($allBlogs)) {
                $originalBlogId = get_current_blog_id();

                foreach ($allBlogs as $blogData) {

                    $tableName = $wpdb->prefix.$blogData->blog_id.'_borlabs_cookie_log';

                    $wpdb->query("DROP TABLE IF EXISTS `".$tableName."`");

                    $tableNameBlockedContentTypes = $wpdb->prefix.$blogData->blog_id.'_borlabs_cookie_blocked_content_types';

                    $wpdb->query("DROP TABLE IF EXISTS `".$tableNameBlockedContentTypes."`");

                    switch_to_blog($blogData->blog_id);

                    delete_option('BorlabsCookieBlockedContentTypesTableCreated');
                    delete_option('BorlabsCookieConfig'); // Before 1.9
                    delete_option('BorlabsCookieStyleVersion'); // Before 1.9
                    delete_option('BorlabsCookieTableCreated');
                    delete_option('BorlabsCookieTableModified');
                    delete_option('BorlabsCookieTranslationUpdated');
                    delete_option('BorlabsCookieVersion');

                    // Find Borlabs Options and delete them
                    $borlabsCookieConfigOptions = $wpdb->get_results('
                        SELECT
                            `option_name`
                        FROM
                            `'.$wpdb->options.'`
                        WHERE
                            `option_name` LIKE "BorlabsCookieConfig_%"
                    ');

                    if (!empty($borlabsCookieConfigOptions)) {
                        foreach ($borlabsCookieConfigOptions as $optionData) {
                            delete_option($optionData->option_name);
                        }
                    }

                    $borlabsCookieStyleOptions = $wpdb->get_results('
                        SELECT
                            `option_name`
                        FROM
                            `'.$wpdb->options.'`
                        WHERE
                            `option_name` LIKE "BorlabsCookieStyleVersion_%"
                    ');

                    if (!empty($borlabsCookieStyleOptions)) {
                        foreach ($borlabsCookieStyleOptions as $optionData) {
                            delete_option($optionData->option_name);
                        }
                    }
                }

                switch_to_blog($originalBlogId);
            }
        } else {

            delete_option('BorlabsCookieBlockedContentTypesTableCreated');
            delete_option('BorlabsCookieConfig'); // Before 1.9
            delete_option('BorlabsCookieStyleVersion'); // Before 1.9
            delete_option('BorlabsCookieTableCreated');
            delete_option('BorlabsCookieTableModified');
            delete_option('BorlabsCookieTranslationUpdated');
            delete_option('BorlabsCookieVersion');

            // Find Borlabs Options and delete them
            $borlabsCookieConfigOptions = $wpdb->get_results('
                SELECT
                    `option_name`
                FROM
                    `'.$wpdb->options.'`
                WHERE
                    `option_name` LIKE "BorlabsCookieConfig_%"
            ');

            if (!empty($borlabsCookieConfigOptions)) {
                foreach ($borlabsCookieConfigOptions as $optionData) {
                    delete_option($optionData->option_name);
                }
            }

            $borlabsCookieStyleOptions = $wpdb->get_results('
                SELECT
                    `option_name`
                FROM
                    `'.$wpdb->options.'`
                WHERE
                    `option_name` LIKE "BorlabsCookieStyleVersion_%"
            ');

            if (!empty($borlabsCookieStyleOptions)) {
                foreach ($borlabsCookieStyleOptions as $optionData) {
                    delete_option($optionData->option_name);
                }
            }
        }

        // Remove license data
        delete_site_option('BorlabsCookieLicenseData');
        delete_site_option('BorlabsCookieLicenseKey');
        delete_site_option('BorlabsCookieLicenseLastCheck');
        delete_site_option('BorlabsCookieUnlinkData');
        delete_site_option('BorlabsCookieNews');
        delete_site_option('BorlabsCookieNewsLastCheck');

        $tableName = $wpdb->prefix.'borlabs_cookie_log';

        $wpdb->query("DROP TABLE IF EXISTS `".$tableName."`");

        $tableNameBlockedContentTypes = $wpdb->prefix.'borlabs_cookie_blocked_content_types';

        $wpdb->query("DROP TABLE IF EXISTS `".$tableNameBlockedContentTypes."`");
    }

    /**
     * deleteFilesInDirectory function.
     *
     * @access public
     * @param mixed $dir
     * @return void
     */
    public function deleteFilesInDirectory($dir)
    {
        if (file_exists($dir)) {
            foreach (new \DirectoryIterator($dir) as $fileInfo) {
                // Ignore . and ..
                if (!$fileInfo->isDot()) {
                    // If folder, delete files in folder
                    if (!$fileInfo->isDir()) {
                        unlink($fileInfo->getPathname());
                    }
                }
            }
        }
    }

    /**
     * isDirectoryEmpty function.
     *
     * @access public
     * @param mixed $dir
     * @return void
     */
    public function isDirectoryEmpty($dir)
    {
        $isEmpty = true;

        if (file_exists($dir)) {
            foreach (new \DirectoryIterator($dir) as $fileInfo) {
                if (!$fileInfo->isDot()) {
                    $isEmpty = false;
                }
            }
        } else {
            // In case something bad happens
            $isEmpty = false;
        }

        return $isEmpty;
    }
}
