<?php

$cms['modules']['admin.mod.php'] = array(
    'name' => __('Admin'),
    'description' => __('Admin module'),
    'url_title' => __('Module page'),
    'url_link' => __('https://coffee-cms.com/en/modules/admin/'),
    'author' => __('Coffee CMS team'),
    'version' => '21.10',
    'files' => array(
        '.cms/mod/admin.mod.php',
        '.cms/js/admin.js',
        '.cms/lang/ru_RU.UTF-8/admin.mod.php',
    ),
    'sort'    => 20,
);

// Return if module disabled
if ( isset($cms['config']['admin.mod.php']['disabled'])
&& $cms['config']['admin.mod.php']['disabled'] === true ) return;

// Find and switch lang
if ( empty( $cms['config']['locale'] ) || !empty( $_GET['locale'] ) ) {

    // Scan all locales
    $cms['locales'] = array('en_US.UTF-8');
    foreach( glob( 'lang/*.UTF-8',  GLOB_ONLYDIR ) as $locale ) {
        $locale = preg_replace( '/.*\//', '', $locale );
        array_push( $cms['locales'], $locale );
    }
    
    // set locale
    if ( empty( $_GET['locale'] ) ) {
        
        $locale = 'en_US.UTF-8';
        $lang   = 'en';
        
    } else {
    
        $locale = $_GET['locale'];
        $lang   = substr( $locale, 0, 2 );
    
    }
    
    $cms['config']['locale'] = $locale;
    $cms['config']['lang'] = $lang;
        
    //cms_save_config();
}


if ( !empty( $cms['config']['locale'] ) ) {
    $translit = $cms['cms_dir'].'/lang/'.$cms['config']['locale'].'/translit.php';
    if ( file_exists( $translit ) ) {
        include_once( $translit );
    }
}

/* На этапе установки URL админки еще не задан.
   Возьмем текущий URL и будем считать что он админский
*/
if ( empty($cms['config']['admin.mod.php']['admin_url']) ) {
    $cms['config']['admin.mod.php']['admin_url'] = $cms['base_path'];
}


if ( empty( $cms['config']['admin.mod.php']['api_url'] ) ) {
    $cms['config']['admin.mod.php']['api_url'] = '/api'.cms_admin_pass_gen();
    $cms['config_writeable'] = cms_save_config();
}

if ( empty( $cms['config']['admin.mod.php']['cron_url'] ) ) {
    $cms['config']['admin.mod.php']['cron_url'] = '/cron'.cms_admin_pass_gen();
    cms_save_config();
}


/* Добавим в перехватчик URLов переход на этап admin при посещении админского URL */
$cms['urls']['^'.$cms['config']['admin.mod.php']['admin_url'].'$'] = 'admin';

$cms['urls']['^'.$cms['config']['admin.mod.php']['api_url'].'$'] = 'api';

$cms['urls']['^'.$cms['config']['admin.mod.php']['cron_url'].'$'] = 'cron';


cms_add_function('admin',         'cms_admin_admin', 9999);
cms_add_function('admin_header',  'cms_admin_admin_header');
cms_add_function('api',           'cms_admin_api');


function cms_admin_admin_header() {
    global $cms;
    echo "<script src='{$cms['base_path']}js/admin.js'></script>";
}


function is_admin() {
    global $cms;
    return 
      isset($_COOKIE['admin_login']) && 
      isset($_COOKIE['admin_password']) &&
      isset($cms['config']['logged'][$_COOKIE['admin_login']]) &&
      ($_COOKIE['admin_password'] === $cms['config']['logged'][$_COOKIE['admin_login']]['password']);
}


// Построение админ меню
function cms_admin_menu() {
    global $cms;
    
    if ( ! empty( $cms['config']['admin_sections'] ) ) {
        $cms['admin_sections'] = $cms['config']['admin_sections'];
    } else {
        $cms['admin_sections'] = array();
    }

    foreach( $cms['config'] as $mod => $mod_cfg ) {
        // each $cms['config']['...mod.php']['menu']
        if ( substr( $mod, -8, 8 ) == '.mod.php' && empty($mod_cfg['disabled']) && isset( $mod_cfg['menu'] ) ) {
            // Перебираем каждый пункт меню у модуля (их может быть много)
            foreach( $mod_cfg['menu'] as $menu => $menu_cfg ) {
                $section = $menu_cfg['section'];
                $conf = $menu_cfg;
                //$conf['page'] = &$cms['admin_pages'][$menu]; // FIXME видимо не используется
                $conf['module'] = $mod;
                // Init section
                if ( empty( $cms['admin_sections'][$section]['title'] ) ) {
                    $cms['admin_sections'][$section]['title'] = __( $section, $mod );
                    if ( $cms['admin_sections'][$section]['title'] === $section ) {
                        $cms['admin_sections'][$section]['title'] = __( $section, 'admin.mod.php' );
                    }
                    $cms['admin_sections'][$section]['sort'] = 10;
                    $cms['admin_sections'][$section]['hide'] = false;
                }
                $cms['admin_sections'][$section]['items'][$menu] = $conf;
            }
        }
    }

    // Sort sections
    cms_asort( $cms['admin_sections'] );

    // Sort items inside sections
    foreach( $cms['admin_sections'] as $section_name => $section ) {
        cms_asort( $cms['admin_sections'][$section_name]['items'] );
    }
}

function cms_admin_admin() {
    global $cms;
    $cms['template'] = 'admin';
    $cms['status'] = '200';
    $cms['stages']['write']['disabled'] = true;
    
    if (!is_admin()) return;
    
    // Save settings
    if (!empty($_POST['change_admin_login'])) {
        $login = trim($_POST['admin_login']);
        $password = trim($_POST['admin_password']);
        $cms['config']['admin.mod.php']['admin_login'] = $login;
        if (!empty($password)) {
            $cms['config']['admin.mod.php']['admin_password'] = $password;
        }
        cms_save_config();
        header('Location: ' . $cms["config"]["admin.mod.php"]["admin_url"]);
        exit;
    }

    $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 777 777"><rect width="777" height="777" style="fill:none"></rect><path d="M426.79,388.5,592.1,223.19a27.15,27.15,0,0,0,0-38.29h0a27.15,27.15,0,0,0-38.29,0L388.5,350.21,223.19,184.9a27.15,27.15,0,0,0-38.29,0h0a27.15,27.15,0,0,0,0,38.29L350.21,388.5,184.9,553.81a27.08,27.08,0,0,0,38.29,38.29L388.5,426.79,553.81,592.1a27.08,27.08,0,0,0,38.29-38.29Z" style="fill:#fff"></path></svg>';
    $rows = '';
    foreach ( $cms['config']['logged'] as $login => $attr ) {
        if ( $login === $_COOKIE['admin_login'] ) {
            $current = 'class=current';
        } else {
            $current = '';
        }
        $rows .= "<div data-logged {$current}><div class=del data-login='{$login}'>{$svg}</div><div>{$attr['date']}</div><div>{$attr['ip']}</div><div>{$attr['user_agent']}</div></div>";
    }

    $logouts = '';
    if ( !empty( $cms['config']['logouted'] ) ) {
        foreach ( $cms['config']['logouted'] as $attr ) {
            $logouts = "<div><div></div><div>{$attr['date']}</div><div>{$attr['ip']}</div><div>{$attr['user_agent']}</div></div>{$logouts}";
        }
    }
    
    // Display settings
    $form = "
    <div class='main-header'></div>
    <div class='main-main'>
        <div class='db-grid'>
            <div class='dbbox'>
                <form method=post class=bdf>
                    <div class=field>
                        <div class='field-name-bd'>".__("Login or Email")."</div>
                        <input name=admin_login type=text value='{$cms['config']['admin.mod.php']['admin_login']}' autocomplete=off class='settingx sto'>
                    </div>
                    <div class=field>
                        <div class='field-name-bd'>".__("Password")."</div>
                        <input name=admin_password type=password value='{$cms['config']['admin.mod.php']['admin_password']}' autocomplete=off class='settingx sto'>
                        <div class='password-eye'></div>
                    </div>
                    <input type=submit value='".__("Save")."' name=change_admin_login class=button-save>
                </form>
            </div>
            
            <div class='dbmanual'>
                <div class=info>
                    <h1>".__('Current logins')."</h1>
                    <div class=grid-table>{$rows}</div>
                </div>
                <div class=info>
                    <h1>".__('Logins history')."</h1>
                    <div class=grid-table>{$logouts}</div>
                </div>
            </div>
            
        </div>
    </div>
    <div class='main-footer'></div>";
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['auth'] ) ) {
        $cms['config']['admin.mod.php']['menu']['auth'] = array(
            'title'    => 'Auth',
            'sort'     => 10,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['auth'] = $form;

   
    // PHP Info

    ob_start();
    phpinfo();
    preg_match( '/<body>(.+)<\/body>/s', ob_get_clean(), $m );
    $page = '
<div class="main-header"></div>
<div class="main-main">
    ' . $m[1] . '
  </div>
<div class="main-footer"></div>
    ';
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['phpinfo'] ) ) {
        $cms['config']['admin.mod.php']['menu']['phpinfo'] = array(
            'title'    => 'PHP Info',
            'sort'     => 30,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['phpinfo'] = $page;


    // Список модулей
    $admin_menu = '
    <div class="main-header"></div>
    <div class="main-main">
      <div class=wrapper-page-grid>';
    // Перебираем config и ищем модули
    foreach( $cms['modules'] as $mod => $mod_cfg ) {
        if ( isset( $cms['config'][$mod]['disabled'] ) && $cms['config'][$mod]['disabled'] === true ) {
            $status = 'disabled';
            $disabled = __('(Disabled)');
        } else {
            $status = 'enabled';
            $disabled = '';
        }
        $descr = "{$mod_cfg['description']}";
        $v     = "<span class=module-version>".__('Version').": {$mod_cfg['version']}</span> ";
        @$v    .= "<span class=module-site><a href='{$mod_cfg['url_link']}' target=_blank class=module-link>{$mod_cfg['url_title']}</a></span> ";
        $v    .= "<span class=module-author>".__('Author').": {$mod_cfg['author']}</span> ";
        $admin_menu .= "
            <div class='pages-box'>
                <div class='cpline style-module' data-module={$mod}>
                    
                    <div class=module-name>
                        <h1 class='{$status}'>{$mod_cfg['name']} {$disabled}</h1>
                        <p class=module-descr>{$descr}</p>
                    </div>

                    <div class=module-buttons>
                        <div class='admin-pagesetting'>
                            <div class='page-name-mobile'><div class=title>{$mod_cfg['name']}</div><div class=close></div></div>
                            <a href=# data-module-enable={$mod} data-module-status={$status}>".__('On')."</a> 
                            <a href=# data-module-disable={$mod} data-module-status={$status}>".__('Off')."</a> 
                            <span class='a-red'>
                            <a href='#' class=module-del data-module-del={$mod}>".__('Delete')."</a>
                            </span>
                        </div>
                    </div>

                    <div class=module-groupval>
                        <p class=module-val>{$v}</p>
                    </div>

                    <div class=module-mobile data-menu-module={$mod}></div>

                    <div class=module-status>
                        <div class='admin-checkpageline {$status}'></div>
                    </div>
                    
                </div>
            </div>
        ";
    }
    $admin_menu .= '
      </div>
    </div>
    <div class="main-footer"></div>';
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['modules'] ) ) {
        $cms['config']['admin.mod.php']['menu']['modules'] = array(
            'title'    => 'Modules',
            'sort'     => 50,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    $cms['admin_pages']['modules'] = $admin_menu;


    // Настройка админского меню

    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['admin.mod.php']['menu']['admin_menu'] ) ) {
        $cms['config']['admin.mod.php']['menu']['admin_menu'] = array(
            'title'    => 'Admin Menu',
            'sort'     => 40,
            'class'    => '',
            'section'  => 'Settings',
            'hide'     => false,
        );
        cms_save_config();
    }
    
    cms_admin_menu();

    // Цикл контейнеров
    $admin_menu = '
    <div class="main-header"></div>
    <div class="main-main">
      <div class=wrapper-page-grid>';
    foreach( $cms['admin_sections'] as $section_name => $section ) {
        if ( isset($section['hide']) && $section['hide'] === true ) {
            $status = 'hidden';
            $hidden = __('(Container Hidden)');
        } else {
            $status = 'showed';
            $hidden = __('(Container)');
        }
        $admin_menu .= "
        <div class='pages-box'>
            <div class='hotsetting' data-am-prop={$section_name} data-type=section>
                <h1>".__('CONTAINER PROPERTIES')."</h1>
                <div class='sett-grid-container'>

                    <div class='sett-grid'>
                        <div class='sett-attribute prop-title'>
                            <div class='settinput-text'>".__('Title').":</div>
                            <div><input name='title' type='text' class='settingx' value='{$section['title']}'></div>
                        </div>
                    </div>
                
                    <div class='sett-grid'>
                        <div class='sett-attribute prop-sort'>
                            <div class='settinput-text'>".__('Sort').":</div>
                            <div><input name='sort' type='text' class='settingx-right-order' value='{$section['sort']}'></div>
                        </div>
                    </div>
                
                </div>
                
                <div class='hotbott'>
                    <a href=# data-am-cancel={$section_name} class='button-close'>".__('Cancel')."</a>
                    <a href=# data-am-delete={$section_name} class='button-delete'>".__('Delete Container')."</a>
                    <a href=# data-am-save data-am-i={$section_name} data-am-fn='admin_menu_save' class='button-save'>".__('Save')."</a>
                </div>

            </div>
            <div class='cpline style-admin-container' data-am-item={$section_name}>

                <div class='admincont-menu-name'>
                    <h1 class='{$status}'>{$section['title']} {$hidden}</h1>
                </div>
                
                <div class='admincont-menu-button'>
                    <div class='admin-pagesetting'>
                        <div class='page-name-mobile'><div class=title>{$mod_cfg['name']} {$disabled}</div><div class=close></div></div>
                        <a href=# class=open-prop      data-am-prop-open={$section_name}>".__('Properties')."</a> 
                        <a href=# class='hide' data-am-show={$section_name} data-am-status={$status}>".__('Show')."</a> 
                        <a href=# class='hide' data-am-hide={$section_name} data-am-status={$status}>".__('Hide')."</a>
                    </div>
                </div>

                <div class='admincont-menu-mobile' data-menu-admin-menu={$section_name}></div>

                <div class='admincont-menu-check'>
                    <div class='admin-checkpageline {$status}'></div>
                </div>
                

            </div>
            <div class='subbox-grid open' data-am-childs={$section_name}>
        ";

        // Цикл пунктов в контейнере
        if ( !empty( $cms['admin_sections'][$section_name]['items'] ) )
        foreach( $cms['admin_sections'][$section_name]['items'] as $iname => $item ) {
            if ( isset( $item['hide'] ) && $item['hide'] === true ) {
                $status = 'hidden';
                $hidden = __('(Hidden)');
            } else {
                $status = 'showed';
                $hidden = '';
            }
            $title = __($item['title'],$item['module']);
            $admin_menu .= "
                <div class='pages-box'>
                    <div class='hotsetting' data-module={$item['module']} data-am-prop={$iname} data-type=menu data-parent-section={$section_name}>
                        <h1>".__('ITEM PROPERTIES')." − {$title}</h1>
                        <div class='sett-grid-container'>
                            <div class='sett-grid'>
                                <div class='sett-attribute prop-parent'>
                                    <div class='settinput-text'>".__('Container').":</div>
                                    <div class=select2-wrapper>
                                        <select class='settingx-right parents-list' data-am-parent='{$section_name}' name=section>";
                                        foreach( $cms['admin_sections'] as $section_name2 => $section2 ) {
                                            if ( $section_name === $section_name2 ) {
                                                $selected = ' selected';
                                            } else {
                                                $selected = '';
                                            }
                                            $admin_menu .= "<option value='{$section_name2}'{$selected}>".__($section2['title'])."</option>";
                                        }
            $admin_menu .= "            </select>
                                    </div>
                                </div>
                            </div>
                        
                            <div class='sett-grid'>
                                <div class='sett-attribute prop-sort'>
                                    <div class='settinput-text'>".__('Sort').":</div>
                                    <div><input name='sort' type='text' class='settingx-right-order' value='{$item['sort']}'></div>
                                </div>
                            </div>
                        
                        </div>
                        
                        <div class='hotbott'>
                            <a href='#' data-am-cancel={$iname} class='button-close'>".__('Cancel')."</a>
                            <a href='#' data-am-reset data-am-i={$iname} data-am-fn='admin_menu_reset' class='button-close'>".__('Reset')."</a>
                            <a href='#' data-am-save data-am-i={$iname} data-am-fn='admin_menu_save' class='button-save'>".__('Save')."</a>
                        </div>
                
                    </div>

                    <div class='cpline style-admin-menu' data-am-item={$iname}>
                        
                        <div class='admin-menu-name'>
                            <h1 class='{$status}'>{$title} {$hidden}</h1>
                        </div>

                        <div class='admin-menu-button'>
                            <div class='admin-pagesetting'>
                                <div class=page-name-mobile><div class=title>mobile</div><div class=close></div></div>
                                <a href=# class=open-prop      data-am-prop-open={$iname}>".__('Properties')."</a> 
                                <a href=# class='hide' data-am-show={$iname} data-am-status={$status}>".__('Show')."</a> 
                                <a href=# class='hide' data-am-hide={$iname} data-am-status={$status}>".__('Hide')."</a>
                            </div>
                        </div>

                        <div class='admin-menu-mobile' data-menu-admin-menu={$iname}></div>

                        <div class='admin-menu-check'>
                            <div class='admin-checkpageline {$status}'></div>
                        </div>
                        
                    </div>
                </div>
            ";
        }
        // Закрытие цикла пунктов в контейнере
        $admin_menu .= "</div></div>";
    }


    // Закрытие цикла контейнеров
    $admin_menu .= '</div>';
    $admin_menu .= '
      <div class=bottompanell>
        <a data-am-add-section class="add-button add-section" href=#>'.__('Add Container').'</a>
      </div>
    </div>
    <div class="main-footer"></div>
    ';

    $cms['admin_pages']['admin_menu'] = $admin_menu;

}


function cms_admin_api() {
    global $cms;

    // PHP_VERSION_ID доступна в версиях PHP 5.2.7 и выше
    if ( !defined( 'PHP_VERSION_ID' ) ) {
        $version = explode( '.', PHP_VERSION );
        define( 'PHP_VERSION_ID', ( $version[0] * 10000 + $version[1] * 100 + $version[2] ) );
    }

    // Login
    if ( !empty( $_POST['fn'] ) && $_POST['fn'] == 'login' ) {
        $cms['status'] = '200';
        // Install process
        $login = trim($_POST['login']);
        $password = trim($_POST['password']);
        if ( empty($cms['config']['admin.mod.php']['admin_login'])
         && empty($cms['config']['admin.mod.php']['admin_password'])
         && (!empty($login) || !empty($password)) ) {
            $cms['config']['admin.mod.php']['admin_login']    = $login;
            $cms['config']['admin.mod.php']['admin_password'] = $password;
            $cms['config']['admin.mod.php']['admin_salt']     = cms_admin_pass_gen(8);
            $cms['config']['admin.mod.php']['admin_url']      = $cms['base_path'].'-admin';
            $_POST['url'] = $cms['config']['admin.mod.php']['admin_url'];
            $link = $cms['url']['scheme'].'://'.$_SERVER['SERVER_NAME'].$cms['config']['admin.mod.php']['admin_url'];
            /* Set Locale and Timezone */
            $cms['config']['locale'] = $_POST['locale'];
            $cms['config']['lang']   = substr( $cms['config']['locale'], 0, 2 );
            $translit = $cms['cms_dir'].'/lang/'.$cms['config']['locale'].'/translit.php';
            if ( file_exists( $translit ) ) {
                include_once( $translit );
            }
            cms_save_config();
            if ( preg_match( '/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,9})(\]?)$/', $cms['config']['admin.mod.php']['admin_login'] ) ) {
                $subject = __('Install finished');
                $body = "<h2>".__('Congratulations!')."</h2>";
                $body .= "<p>".__('Install finished').".</p>";
                $body .= "<h4>".__('Credentials for login')."</h4>";
                $body .= "<p>".__('Login URL').": <a href='{$link}'>{$link}</a></p>";
                $body .= "<p>".__('Login').": {$_POST['login']}</p>";
                $body .= "<p>".__('Password').": {$_POST['password']}</p>";
                $body .= "<p></p><p>".__('Please login and setup database').".</p><p></p>";
                cms_email(array(
                    'type' => 'text/html',
                    'from_email' => 'noreply@'.$_SERVER['SERVER_NAME'],
                    'from_name' => $_SERVER['SERVER_NAME'],
                    'to_email' => $_POST['login'],
                    'subject' => $subject,
                    'email_body' => $body
                    ));
            }
        }
        // Check login and password
        if ( $_POST['login'] === $cms['config']['admin.mod.php']['admin_login'] && 
             $_POST['password'] === $cms['config']['admin.mod.php']['admin_password'] &&
             $_POST['url'] === $cms['config']['admin.mod.php']['admin_url'] )
        {

            $d = date('Y-m-d H:i:s');
            $login = sha1( $cms['config']['admin.mod.php']['admin_login'].$cms['config']['admin.mod.php']['admin_salt'].$d );
            $password = sha1( $cms['config']['admin.mod.php']['admin_password'].$cms['config']['admin.mod.php']['admin_salt'].$d );
            
            // Prepend New Session
            if ( !isset( $cms['config']['logged'] ) ) { $cms['config']['logged'] = array(); }
            $cms['config']['logged'] = array( $login => array(
                'password'   => $password,
                'ip'         => $_SERVER['REMOTE_ADDR'],
                'date'       => $d,
                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            ) ) + $cms['config']['logged'];

            /* Set Locale and Timezone */
            $cms['config']['locale'] = $_POST['locale'];
            $cms['config']['lang']   = substr( $cms['config']['locale'], 0, 2 );
            $translit = $cms['cms_dir'].'/lang/'.$cms['config']['locale'].'/translit.php';
            if ( file_exists( $translit ) ) {
                include_once( $translit );
            }

            if ( cms_save_config() ) {
                if ( PHP_VERSION_ID < 70300 ) {
                    setcookie('admin_login', $login );
                    setcookie('admin_password', $password );
                } else {
                    setcookie('admin_login', $login, array( 'SameSite' => 'Strict' ) );
                    setcookie('admin_password', $password, array( 'SameSite' => 'Strict' ) );
                }
            }

            $link = $cms['url']['scheme'].'://'.$_SERVER['SERVER_NAME'].$cms['config']['admin.mod.php']['admin_url'];
            exit( json_encode( array(
                'link'  => $link,
            ) ) );
        } else {
            $cms['config']['locale'] = $_POST['locale'];
            exit( json_encode( array(
                'info_text'  => __("Access denied"),
                'info_class' => 'info-error',
                'info_time'  => 5000,
            ) ) );
        }
    }

    // Logout and Admin Menu
    if ( !empty( $_POST['fn'] ) && is_admin() ) {
        switch ( $_POST['fn'] ) {

            case 'logout':
                $cms['status'] = '200';
                if ( empty($_POST['sess']) ) {
                    if ( PHP_VERSION_ID < 70300 ) {
                        setcookie('admin_login', '' );
                        setcookie('admin_password', '' );
                    } else {
                        setcookie('admin_login', '', array( 'SameSite' => 'Strict' ) );
                        setcookie('admin_password', '', array( 'SameSite' => 'Strict' ) );
                    }
                    $login = $_COOKIE['admin_login'];
                    $result = 'refresh';
                } else {
                    $login = $_POST['sess'];
                    if ( $_POST['sess'] === $_COOKIE['admin_login'] ) {
                        $result = 'refresh';
                    } else {
                        $result = 'ok';
                    }
                }

                if ( !isset($cms['config']['logouted']) ) { $cms['config']['logouted'] = array(); }
                array_push( $cms['config']['logouted'], $cms['config']['logged'][$login] );
                $cms['config']['logouted'] = array_slice( $cms['config']['logouted'], -10 );
                unset($cms['config']['logged'][$login]);
                cms_save_config();

                exit( json_encode( array(
                    'info_text'  => __("Logout completed"),
                    'info_class' => 'info-success',
                    'info_time'  => 5000,
                    'result'     => $result,
                ) ) );
            break;

            case 'admin_menu_save':
                $cms['status'] = '200';
                switch ($_POST['type']) {
                    case 'section':
                        $cms['config']['admin_sections'][ $_POST['item'] ]['title'] = $_POST['title'];
                        $cms['config']['admin_sections'][ $_POST['item'] ]['sort']  = (int)$_POST['sort'];
                        break;
                    case 'menu':
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['section'] = $_POST['section'];
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['sort']    = (int)$_POST['sort'];
                        break;
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;
            
            case 'admin_menu_reset':
                $cms['status'] = '200';
                unset( $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ] );
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;
            

            case 'admin_menu_hide':
                $cms['status'] = '200';
                $hide = $_POST['hide'] === 'true';
                switch ($_POST['type']) {
                    case 'section':
                        $cms['config']['admin_sections'][ $_POST['item'] ]['hide'] = $hide;
                        break;
                    case 'menu':
                        $cms['config'][ $_POST['module'] ]['menu'][ $_POST['item'] ]['hide'] = $hide;
                        break;
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'admin_menu_add_section':
                $cms['status'] = '200';
                $n = 1;
                while ( isset( $cms['config']['admin_sections']['Container'.$n] ) ) {
                    $n++;
                }
                $cms['config']['admin_sections']['Container'.$n] = array(
                    'title' => 'Container'.$n,
                    'sort'  => (count($cms['config']['admin_sections'])+1)*10,
                    'hide' => false,
                );
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'admin_menu_del':
                $cms['status'] = '200';
                unset($cms['config']['admin_sections'][ $_POST['item'] ]);
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'module_disable':
                $cms['status'] = '200';
                if ( in_array( $_POST['module'], array(
                    'admin.mod.php',
                    'base.mod.php',
                    'menu.mod.php',
                    'pages.mod.php',
                    /*'sitemap.mod.php',*/
                    'template.mod.php', ) ) )
                {
                    exit( json_encode( array(
                        'info_text'  => __('See how-to').' <a href="https://coffee-cms.com/" target=_blank>'.__('Disable standard modules').'</a>',
                        'info_class' => 'info-error',
                        'info_time'  => 0,
                    ) ) );
                }
                if ( $_POST['disable'] === 'true' ) {
                    $cms['config'][$_POST['module']]['disabled'] = true;
                } else {
                    unset($cms['config'][$_POST['module']]['disabled']);
                }
                cms_save_config();
                exit( json_encode( array(
                    'info_text'  => __('OK'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'module_del':
                $cms['status'] = '200';
                if ( in_array( $_POST['module'], array(
                    'admin.mod.php',
                    'base.mod.php',
                    'menu.mod.php',
                    'pages.mod.php',
                    'sitemap.mod.php',
                    'template.mod.php',
                    'update.mod.php', ) ) )
                {
                    $text = __('Delete following files:');
                    foreach( $cms['modules'][$_POST['module']]['files'] as $file ) {
                        $text .= "<br>{$file}";
                    }
                    $class = 'info-error';
                    $time  = 0;
                } else {
                    foreach( $cms['modules'][$_POST['module']]['files'] as $file ) {
                        unlink($cms['site_dir'].'/'.$file);
                    }
                    $text  = __('OK');
                    $class = 'info-success';
                    $time  = 2000;
                }
                exit( json_encode( array(
                    'info_text'  => $text,
                    'info_class' => $class,
                    'info_time'  => $time,
                ) ) );
            break;
        }
        
    }
}


function cms_admin_pass_gen($count = 8) {
    $chars = '0123456789AaBbCcDdEeFfGgHhiJjKkLMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $strlen = strlen($chars)-1;
    $password = '';
    while ($count--) {
        $password .= $chars[rand(0,$strlen)];
    }
    return $password;
}
