<?php
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Model for ciext_help
 *
 * @author Roman Ratsun
 */
class ciext_help_model extends CI_Model
{

    public function __construct()
    {
        // prepare parser
        $this->prepare_parser();
    }

    public function get_documentation_content()
    {
        // prepare default
        $content = [
            'modules' => []
        ];

        // prepare data
        $applicationPath = dirname(dirname(dirname(dirname(BASEPATH))));

        // get modules
        $modules = $this->get_molules();

        if (!empty($modules)) {
            foreach ($modules as $item) {
                $content['modules'][] = [
                    'name'    => $item['name'],
                    'content' => $this->readme_parser->text(file_get_contents($applicationPath.'/'.$item['path']))
                ];
            }
        }

        return $content;
    }

    /**
     * Get all modules
     *
     * @return array
     */
    protected function get_molules()
    {
        // prepare data
        $data = [];

        // find modules and set data
        foreach (array_keys($this->config->item('modules_locations')) as $loc) {
            $tmp = scandir($loc);
            foreach ($tmp as $mod_name) {
                // prepare data
                $is_module          = file_exists($loc.$mod_name.'/controllers/'.$mod_name.'_install.php');
                $path               = '';
                $readme_file_path_1 = $loc.$mod_name.'/readme.md';
                $readme_file_path_2 = $loc.$mod_name.'/README.md';
                if (file_exists($readme_file_path_1)) {
                    $path = $readme_file_path_1;
                } else
                if (file_exists($readme_file_path_2)) {
                    $path = $readme_file_path_2;
                }

                // add module
                if ($is_module && !empty($path)) {
                    $data[] = [
                        'name' => $mod_name,
                        'path' => $path
                    ];
                }
            }
        }

        return $data;
    }

    /**
     * Prepare parser
     */
    protected function prepare_parser()
    {
        // load library
        $this->load->library('ciext_help/readme_parser');

        $this->readme_parser->setBreaksEnabled(true);
        $this->readme_parser->setMarkupEscaped(true);
        $this->readme_parser->setUrlsLinked(true);
    }
}
