<?php
class Cf_hooks
{
    public function __construct()
    {
        $this->ci = &get_instance();

        //TODO: Do not use hardcode path here
        $this->modulesPath = realpath(APPPATH . 'modules');

        $this->initialize();
    }

    /**
     * Fill $GLOBALS[HOOKS] array
     *
     */
    public function initialize()
    {
        // Get the module configuration file from each module
        foreach ($this->getEnabledModules() as $moduleName) {
            $fileToInclude = sprintf('%s/%s/config/hooks.php', $this->modulesPath, $moduleName);
            if (file_exists($fileToInclude)) {
                @include $fileToInclude;
            }
        }
    }

    /**
     * Return array of enabled modules
     *
     * @return array
     */
    public function getEnabledModules()
    {
        $installedModules = $this->scanDir($this->modulesPath);

        $installedModules = array_flip($installedModules);

        $this->ci->load->model('apps_model');

        $enabledModules = $this->ci->apps_model->getEnabledApplicationsIds();

        $enabled = [];

        foreach ((array) $enabledModules as $item => $name) {
            if (isset($installedModules[$item])) {
                $enabled[$item] = $item;
            }
        }

        return $enabled;
    }

    /**
     * Scan a directory and return its files and folders as an array
     * @param string
     * @return array
     */
    public function scanDir($pathToFolder)
    {
        // Add a trailing slash
        if (substr($pathToFolder, -1, 1) != '/') {
            $pathToFolder .= '/';
        }

        $files = [];

        // Scan directory
        foreach (scandir($pathToFolder) as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }

            $files[] = $file;
        }

        return $files;
    }
}
