<?php
/**
 * Class LayoutBrowser
 *
 * Create nav structure for css layouts
 *
 * @author  Paul McAvoy <paul.mcavoy@mtcmedia.co.uk>
 * @version 0.1
 */
Class LayoutBrowser
{

    public $layout_directories = [];
    public $html = '';
    public $template_info = [];
    public $nav_array = [];

    /**
     * List directories within css folder and add them to array with details
     *
     * @access public
     * @static
     * @params string $dir path to layout directory
     * @return Array
     */
    public static function getDirectories($dir)
    {
        $cdir = scandir($dir);
        $layout_directories = [];
        $excludes = [
            '.',
            '..',
            'plugin_includes'
        ];

        foreach ($cdir as $key => $value) {
            if (!in_array($value, $excludes)) {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
                    $layout_directories[$value]['directory_info'] = [
                        'directory_name' => $value,
                        'directory_path' => $dir
                    ];

                    $directories = self::getDirectories($dir . DIRECTORY_SEPARATOR . $value);

                    if (!empty($directories)) {
                        $layout_directories[$value]['directory_info']['children'] = $directories;
                    }

                    if (!array_key_exists('children', $layout_directories[$value]['directory_info'])) {
                        $layout_directories[$value]['template_info'] = self::addTemplateInfo($value, $dir);
                    }
                }
            }
        }

        return $layout_directories;
    }

    /**
     * Add template info to directories array
     *
     * @access public
     * @static
     * @params string $dir path to layout directory
     * @return Array
     */
    public static function getTemplates($dir)
    {

        // add template info for each directory
        $template_info = self::getDirectories($dir);

        return $template_info;
    }

    /**
     * add template info to array
     *
     * @access public
     * @static
     * @params string $dir_name name of path
     * @params string $dir path to directory of layout file
     * @return object
     */
    public static function addTemplateInfo($dir_name, $dir)
    {
        // new recursive iterator
        $iterator = self::iterator($dir);
        $template_info = [];

        foreach ($iterator as $directory) {
            // get path name of layout template
            $path_name = $directory->getPathname();
            // get folder name of layout template
            $folder_name = $directory->getFilename();

            if ($folder_name === $dir_name) {
                foreach (glob($path_name . "/*.twig") as $key => $file_name) {

                    // get template name of layout template by reading first line and matching format of template name
                    if (($f = @fopen($file_name, 'r')) !== null) {
                        $first_line = fgets($f);
                        preg_match("/^{# Template : ([^(#})]+) #}/", $first_line, $matches);
                        if (!empty($matches[1])) {
                            $template_name = $matches[1];
                        }
                        fclose($f);
                    }

                    // add above to array

                    if (!empty($template_name)) {
                        $template_info[] = [
                            'path_name' => $path_name,
                            'folder_name' => $folder_name,
                            'file_name' => $file_name,
                            'template_name' => $template_name
                        ];
                    }
                }
            }
        }

        return $template_info;

    }

    /**
     * Iterator over direcotries
     *
     * @access public
     * @static
     * @params string $dir path to layout template
     * @return object
     */
    public static function iterator($dir)
    {

        $dir_iterator = new RecursiveDirectoryIterator($dir);
        $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
        $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);

        return $iterator;

    }

    /**
     * Reconstruct array into useable tree for use with twig
     *
     * @access public
     * @static
     * @params array $navigation navigation info links, names
     * @return Array
     */
    public static function buildNavigation(array $navigation)
    {
        $i = 0;

        foreach ($navigation as $key => $link) {

            // create name for directory
            $nav_array[$i] = [
                'template_name' => str_replace('-', ' ', $link['directory_info']['directory_name']),
                'template_link' => ''
            ];

            // if children array exists run this function again
            if (array_key_exists('children', $link['directory_info'])) {

                $nav_array[$i]['children'] = self::buildNavigation($link['directory_info']['children']);

            }

            // if template info exists we are at the end of the loop add the relevant info
            if (!empty($link['template_info'])) {

                // loop through template info and to array
                foreach ($link['template_info'] as $link) {

                    $nav_array[$i]['children'][] = [
                        'template_name' => str_replace('-', ' ', $link['template_name']),
                        'template_link' => '/css/index.php?twig_template_name=' . str_replace(SITE_PATH . '/core/css', '', $link['file_name'])
                    ];

                }

            }

            $i++;
        } // end foreach

        return $nav_array;

    }

    /**
     * Get output css folder structure as navigation
     *
     * @access public
     * @static
     * @params string $dir path to layout directory
     * @return strong
     */
    public static function getNavigation($dir)
    {
        $nav = self::getTemplates($dir);

        return self::buildNavigation($nav);
    }

    /**
     * Build array of stylesheets and script files used
     *
     * @access public
     * @static
     * @params string $template path to layout template
     * @return Array
     */
    public static function getAssets($template)
    {
        $path_name = SITE_PATH . '/core/css' . dirname($template);

        $template_info = [
            'styles' => [],
            'scripts' => [],
        ];

        // get less
        foreach (glob($path_name . '/*.less') as $key => $file_name) {

            $style_name = str_replace(SITE_PATH, '', $file_name);

            $template_info['styles'][] = $style_name;
        }

        // get js
        foreach (glob($path_name . '/*.js') as $key => $file_name) {

            $script_name = str_replace(SITE_PATH, '', $file_name);

            $template_info['scripts'][] = $script_name;
        }

        return $template_info;
    }

    /**
     * Get all less files with css folder and update the import path
     *
     * @access public
     * @static
     * @params string $less_import path to import.less file
     * @return boolean
     */
    public static function updateImportPath($less_import)
    {
        // import less file that is here
        $import = "@import '" . THEME_PATH . "/css/mtc_style.less';\n";

        // get file contents
        $contents = file($less_import, FILE_SKIP_EMPTY_LINES);

        // update first line;
        $contents[0] = $import;

        // update file
        file_put_contents($less_import, $contents, LOCK_EX);

        return true;

    }

    /**
     * Return array of files parent directories
     *
     * @access public
     * @static
     * @params string $templates_path path to layout template
     * @return array
     */
    public static function getTemplateDirectories($templates_path)
    {
        $template_directories = [];

        $template_directories = explode('/', $templates_path);

        return $template_directories;
    }

}
