<?php
/**
 * i-doit
 *
 * @package     i-doit
 * @subpackage  Licensing
 * @author      Dennis Stücken <dstuecken@i-doit.org>
 * @version     1.5
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

use idoit\Module\License\LicenseServiceFactory;

/**
 * Class isys_module_licence
 */
class isys_module_licence extends isys_module implements isys_module_interface
{
    // Define, if this module shall be displayed in the named menus.
    const DISPLAY_IN_MAIN_MENU   = false;
    const DISPLAY_IN_SYSTEM_MENU = false;

    // @phpstan-ignore-next-line
    private $m_userrequest = null;

    /**
     * Show nag screen if user is not licenced.
     */
    public static function show_nag_screen()
    {
        // @phpstan-ignore-next-line
        if (C__ENABLE__LICENCE) {
            if ($_GET[C__GET__MODULE_ID] != defined_or_default('C__MODULE__SYSTEM') && $_GET[C__GET__SETTINGS_PAGE] !== 'licence_overview') {
                if (isset($_SESSION['licenced']) && $_SESSION['licenced'] === false) {
                    isys_component_signalcollection::get_instance()
                        ->connect('system.gui.beforeRender', function () {
                            register_shutdown_function(function () {
                                echo '<script>openFullscreenPopup("license-warning");</script>';
                            });
                        });
                }
            }
        }
    }

    /**
     * Initializes the module.
     *
     * @param   isys_module_request & $p_req
     *
     * @return  boolean
     */
    public function init(isys_module_request $p_req)
    {
        if (is_object($p_req)) {
            $this->m_userrequest = &$p_req;

            return true;
        }

        return false;
    }

    /**
     * This method builds the tree for the menu.
     *
     * @param   isys_component_tree $p_tree
     * @param   boolean             $p_system_module
     * @param   integer             $p_parent
     *
     * @author  Leonard Fischer <lfischer@i-doit.org>
     * @since   0.9.9-7
     * @see     isys_module::build_tree()
     */
    public function build_tree(isys_component_tree $p_tree, $p_system_module = true, $p_parent = null)
    {
        ;
    }

    /**
     * Starts module process.
     */
    public function start()
    {
        ;
    }

    /**
     * Verifys licence status and saves it in session variable licenced and licence_data
     *
     * @return void
     * @throws Exception
     */
    public function verify()
    {
        global $g_license_token;

        $licenseService = LicenseServiceFactory::createDefaultLicenseService(
            isys_application::instance()->container->get('database_system'),
            $g_license_token
        );

        $isLicensed = $licenseService->isTenantLicensed(isys_application::instance()->container->get('session')->get_mandator_id());

        $_SESSION["licenced"] = $isLicensed;
        $_SESSION["licensed_addons"] = $licenseService->getLicensedAddOns();
    }

    /**
     * Find out about exceeded usage.
     *
     * @return bool
     * @see ID-8586 Implement a more drastic approach.
     */
    public function isThisTheEnd(): bool
    {
        try {
            $tenantSettings = isys_application::instance()->container->get('settingsTenant');

            if (!$_SESSION["licenced"]) {
                $startOfEnd = $tenantSettings->get('system.start-of-end', false);

                if (!$startOfEnd) {
                    $tenantSettings->set('system.start-of-end', date('Y-m-d'));
                } elseif (strtotime($startOfEnd) !== false) {
                    return (new DateTime($startOfEnd))->diff(new DateTime())->days > 30;
                }
            } else {
                $tenantSettings->remove('system.start-of-end');
            }
        } catch (Throwable $e) {
            // Do nothing.
        }

        return false;
    }

    /**
     * @return bool
     */
    public function isTrial(): bool
    {
        global $g_license_token;
        $licenseService = LicenseServiceFactory::createDefaultLicenseService(isys_application::instance()->container->get('database_system'), $g_license_token);

        return $licenseService->isEvaluation();
    }

    /**
     * @param isys_component_database $p_database
     * @param null                    $p_licence_id
     *
     * @return isys_component_dao_result
     */
    public function get_licence(isys_component_database $p_database, $p_licence_id = null)
    {
        $l_dao_mandator = new isys_component_dao_mandator($p_database);

        $l_sql = 'SELECT * FROM isys_licence WHERE TRUE';

        if (!is_null($p_licence_id)) {
            $l_sql .= ' AND isys_licence__id = ' . $l_dao_mandator->convert_sql_id($p_licence_id);
        }

        return $l_dao_mandator->retrieve($l_sql . ';');
    }

    /**
     * @param isys_component_database $p_database
     * @param                         $p_id
     *
     * @return bool
     */
    public function delete_licence(isys_component_database $p_database, $p_id)
    {
        $l_dao = new isys_component_dao($p_database);
        if ($l_dao->update("DELETE FROM isys_licence WHERE isys_licence__id = '" . $p_database->escape_string($p_id) . "';")) {
            $l_dao->apply_update();
        }

        return true;
    }

    /**
     * Removes all client licences which are childs of the specified parent Licence
     *
     * @param isys_component_database $database
     * @param                         $parentLicenceId
     *
     * @return bool|int
     * @author   Van Quyen Hoang <qhoang@i-doit.com>
     */
    public function deleteLicenceByParentLicence(isys_component_database $database, $parentLicenceId)
    {
        $dao = isys_component_dao::factory($database);

        $sqlDelete = 'DELETE FROM isys_licence WHERE isys_licence__isys_licence__id = ' . $dao->convert_sql_id($parentLicenceId) . ';';
        if ($update = $dao->update($sqlDelete)) {
            $affectedRows = $dao->affected_after_update();

            return $dao->apply_update() ? $affectedRows : false;
        }

        return false;
    }
}
