<?php

namespace CCDN\Controllers;

use CCDN\Helpers\DB\Model;
use CCDN\Helpers\Facade\Cache;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Settings;
use Exception;

class DeletePluginController
{

    public function delete()
    {
        $urlAdmin = Url::toAdminPanel();
        Cache::clear();

        clear_cache();

        $this->deleteFromDB(Settings::PLUGIN_NAME);
        $this->deleteFilesFromFolder(Settings::ASSETS_PATH);
        $this->deleteFilesFromFolder(Settings::PLUGIN_PATH);

        @unlink(ENGINE_DIR . '/ajax/ccdn.php');
        @unlink(ENGINE_DIR . '/inc/ccdn.php');
        @unlink(ENGINE_DIR . '/modules/ccdn.php');
        @unlink(ENGINE_DIR . '/classes/CCDN/ccdn.class.php');
        @unlink(ENGINE_DIR . '/modules/ccdn-calendar-fullstory.php');
        @unlink(ENGINE_DIR . '/modules/ccdn-calendar-main.php');
        @unlink(ENGINE_DIR . '/modules/ccdn-franchise-parts.php');

        header('Location: ' . $urlAdmin, true, 301);
    }

    /**
     * @param string $pluginSlugName
     *
     * @return void
     */
    protected function deleteFromDB($pluginSlugName)
    {
        $model = new Model();
        $prefix = PREFIX;

        global $config;

        $model->query("DELETE FROM `{$prefix}_admin_sections` WHERE `name`='{$pluginSlugName}'");
        $model->deleteTable(Settings::SETTINGS_TABLE);

        if ((int)$config['version_id'] >= 13) {
            $pluginID = $model->select("SELECT `id` FROM `{$prefix}_plugins` WHERE `name`='{$pluginSlugName}'");
            $pluginID = $pluginID['id'];
            $model->query("DELETE FROM `{$prefix}_plugins` WHERE `id`='{$pluginID}'");
            $model->query("DELETE FROM `{$prefix}_plugins_files` WHERE `id`='{$pluginID}'");
        }
    }


    /**
     * Removes a directory (and all its content) recursively.
     *
     * @param string $dir
     *
     * @return bool
     */
    protected function deleteFilesFromFolder($dir)
    {
        if (!is_dir($dir)) {
            return false;
        }
        if (!is_link($dir)) {
            if (!($handle = opendir($dir))) {
                return false;
            }
            while (($file = readdir($handle)) !== false) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                $path = $dir . DIRECTORY_SEPARATOR . $file;
                if (is_dir($path)) {
                    $this->deleteFilesFromFolder($path);
                } else {
                    $this->unlink($path);
                }
            }
            closedir($handle);
        }
        if (is_link($dir)) {
            $this->unlink($dir);
        } else {
            rmdir($dir);
        }
    }

    /**
     * Removes a file or symlink in a cross-platform way
     *
     * @param string $path
     *
     * @return bool
     */
    protected function unlink($path)
    {
        $isWindows = DIRECTORY_SEPARATOR === '\\';

        if (!$isWindows) {
            return unlink($path);
        }

        if (is_link($path) && is_dir($path)) {
            return rmdir($path);
        }

        try {
            return unlink($path);
        } catch (Exception $e) {
            if (function_exists('exec') && file_exists($path)) {
                exec('DEL /F/Q ' . escapeshellarg($path));

                return !file_exists($path);
            }

            return false;
        }
    }

}
