<?php

/*
 * The Black Sheep Research Library for Joomla applications
 * Copyright (c) 2017-23 Black Sheep Research
 * Author: Martin Brampton martin@black-sheep-research.com
 * Web: https://black-sheep-research.com
 * License: GNU General Public License version 2
 */
namespace BlackSheepResearch\Component\UserPoints\Site\Problems;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Installer\Installer;

class ExtensionHelper {
    
    public static function extensionEntry ($name, $type='component', $folder='') {
        $db = SQL::getInstance();
        $sql = "SELECT * FROM `#__extensions` WHERE `element` = {$db->quote($name)} AND `type` = {$db->quote($type)}";
        if ('plugin' == $type AND $folder) {
            $sql .= " AND `folder` = '$folder'";
        }
        $sql .= ' LIMIT 1';
        $db->setQuery($sql);
        return $db->loadObject();
    }
    
    public static function isInstalled ($name, $type='component', $folder='') {
        return (0 != is_object(self::extensionEntry($name, $type, $folder)));
    }
    
    public static function isEnabled ($name, $type='component', $folder='') {
        $extension = self::extensionEntry($name, $type, $folder);
        return (is_object($extension) AND $extension->enabled);
    }
    
    public static function toggleEnable (int $enabled, $type='component', $folder='', $name=[]) {
        $db = SQL::getInstance();
        $namelist = $db->quote(implode("','", (array)$name));
        $sql = "UPDATE #__extensions SET `enabled` = $enabled WHERE `type` = {$db->quote($type)} AND element IN ($namelist)";
        if ('plugin' == $type AND $folder) {
            $sql .= " AND `folder` == {$db->quote($folder)}";
        }
        $db->setQuery($sql);
        $db->execute();
    }
    
    public static function installFromPackage ($packagedirectory) {
        $installer = new Installer();
        $installer->setOverwrite(true);
        $installer->install(JPATH_SITE . $packagedirectory);
    }
    
}