<?php

$cms['modules']['pages.mod.php'] = array(
    'name' => __('Pages', 'pages.mod.php'),
    'description' => __('Module for edditing pages', 'pages.mod.php'),
    'url_title' => __('Module page'),
    'url_link' => __('https://coffee-cms.com/en/modules/pages/', 'pages.mod.php'),
    'author' => __('Coffee CMS team'),
    'version' => '21.03',
    'files' => array(
        '.cms/mod/pages.mod.php',
        '.cms/js/pages.js',
    ),
    'sort'    => 20,
);

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


cms_add_function('create_tables', 'cms_pages_create_tables');
cms_add_function('query', 'cms_pages_query');
cms_add_function('admin', 'cms_pages_admin');
cms_add_function('admin_header', 'cms_pages_admin_header');
cms_add_function('api', 'cms_pages_api');

function cms_pages_admin_header() {
    global $cms;
    $ver = "5.59.2";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror-{$ver}/lib/codemirror.css'>";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror-{$ver}/addon/hint/show-hint.css'>";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror-{$ver}/addon/dialog/dialog.css'>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/lib/codemirror.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/hint/show-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/hint/xml-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/hint/html-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/selection/active-line.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/search/search.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/search/searchcursor.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/search/jump-to-line.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/addon/dialog/dialog.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/mode/xml/xml.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/mode/javascript/javascript.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/mode/css/css.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror-{$ver}/mode/htmlmixed/htmlmixed.js'></script>";

    echo "<script src='{$cms['base_path']}js/pages.js'></script>";
    echo "<script src='{$cms['base_path']}js/select2.min.js'></script>";
    echo "<script src='{$cms['base_path']}lang/select2/{$cms['config']['lang']}.js'></script>";
}


function cms_pages_api() {
    global $cms;
    if (!is_admin()) return;
    if (empty($cms['base'])) cms_base_connect();
    if (!empty($_POST['fn'])) {
        
        switch ($_POST['fn']) {

            case 'create_page':
                $cms['status'] = '200';
                if ( empty( $cms['base'] ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Please connect to database', 'pages.mod.php'),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
                /* Определить URL родительской */
                if ( $pid = (int) $_POST['pid'] ) {
                    $q = "SELECT url FROM pages WHERE id='{$pid}'";
                    if ( $r = mysqli_query( $cms['base'], $q ) ) {
                        $parent = mysqli_fetch_assoc( $r );
                    }
                } else {
                    $parent['url'] = $cms['base_path'];
                }
                
                /* Вставить в базу и получить id */
                $created = date('Y-m-d H:i:s');
                $type = 'page';
                $q = "INSERT INTO pages SET created='{$created}', type='{$type}', pid={$pid}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    $id = mysqli_insert_id( $cms['base'] );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Error creating page: ', 'pages.mod.php') . mysqli_error( $cms['base'] ),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }

                /* Создать заголовок, url и обновить в базе */
                $title     = mysqli_real_escape_string( $cms['base'], __('Page', 'pages.mod.php') . ' ' . $id );
                $short_url = strtolower( cms_translit( __('Page', 'pages.mod.php') . ' ' . $id ) );
                $url       = mysqli_real_escape_string( $cms['base'], $parent['url'] . $short_url . '/' );
                //$short_url = mysqli_real_escape_string( $cms['base'], $short_url );
                $short_url = '';
                if (strlen($_POST['sort'])) {
                    if ($_POST['sort2']) {
                        $sort = (int)(( $_POST['sort'] + $_POST['sort2'] ) / 2);
                    } else {
                        $sort = $_POST['sort'] + 10;
                    }
                } else {
                    $sort      = $id * 10;
                }
                $q = "UPDATE pages SET title='{$title}', short_url='{$short_url}', url='{$url}', sort={$sort} WHERE id={$id}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Page created', 'pages.mod.php'),
                        'info_class' => 'info-success',
                        'info_time'  => 1000,
                        'list'       => cms_pages_get_pages_list(),
                        'parents'    => cms_pages_get_parents_list(),
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Error creating page', 'pages.mod.php'),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;

            case 'save_prop':
                $cms['status'] = '200';
                cms_clear_cache();
                $id          = (int) $_POST['id'];
                $pid         = (int) $_POST['pid'];
                $sort        = (int) $_POST['sort'];
                $title       = mysqli_real_escape_string( $cms['base'], $_POST['title'] );
                $seo_title   = mysqli_real_escape_string( $cms['base'], $_POST['seo_title'] );
                $description = mysqli_real_escape_string( $cms['base'], $_POST['description'] );

                // Извлекаем настройки для сравнения
                $q = "SELECT id, pid, type_url, short_url, sort, created FROM pages WHERE id={$id}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    $page = mysqli_fetch_assoc( $r );
                    // Есть ли дочерние
                    //$q = "SELECT id FROM pages WHERE pid={$id} LIMIT 1";
                    //$r = mysqli_query( $cms['base'], $q );
                    //$page['has_child'] = mysqli_fetch_assoc( $r );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __("This page not found", "pages.mod.php"),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }

                // Нужно обновлять весь список если изменился:
                // - родитель страницы
                // - сортировка
                $update_list = false;
                if ( $pid != $page['pid'] || $sort != $page['sort'] ) {
                    $update_list = true;
                }


                // Короткий URL
                if ( $_POST['type_url'] === 'auto' ) {
                    // Определяем URL родителя
                    $q = "SELECT url FROM pages WHERE id={$pid}";
                    if ( $r = mysqli_query( $cms['base'], $q ) ) {
                        $parent = mysqli_fetch_assoc( $r );
                    } else {
                        $parent['url'] = $cms['base_path'];
                    }
                    if ( substr( $parent['url'], 0, 1 ) !== '/' ) { $parent['url']  = '/' . $parent['url']; }
                    if ( substr( $parent['url'], -1 )   !== '/' ) { $parent['url'] .= '/'; }
                    // Если короткий url не задан, то создаем из заголовка
                    if ( empty( $_POST['url'] ) ) {
                        $_POST['url'] = strtolower( cms_translit( $_POST['title'] ) );
                    }
                    //$_POST['url'] = strtr( $_POST['url'], array( '.' => '' ) );
                    $short_url = mysqli_real_escape_string( $cms['base'], $_POST['url'] );
                    $new_url   = $parent['url'] . $_POST['url'] . '/';
                    $new_url   = strtr( $new_url, array( '///' => '/' ) );
                    $url       = mysqli_real_escape_string( $cms['base'], $new_url );
                    // Check dupl
                    if ( $r = mysqli_query( $cms['base'], "SELECT COUNT(*) FROM pages WHERE url='{$url}' AND id<>{$id}" ) ) {
                        if ( $cnt = mysqli_fetch_assoc( $r ) ) {
                            if ( $cnt['COUNT(*)'] > 0 ) {
                                exit( json_encode( array(
                                    'info_text'  => __('Duplicate URL.', 'pages.mod.php'),
                                    'info_class' => 'info-error',
                                    'info_time'  => 5000,
                                ) ) );
                            }
                        }
                    }
                    $update_url = " short_url='{$short_url}', url='{$url}' ";
                    
                    $update_list = cms_pages_update_childs_url( $id, $new_url ) || $update_list;
                    
                } elseif ( $_POST['type_url'] === 'manual' ) {
                    # Полный URL
                    # ...
                }

                if ( empty( $_POST['date'] ) ) { $_POST['date'] = '0000-00-00'; }
                if ( empty( $_POST['time'] ) ) { $_POST['time'] = '00:00'; }
                $created   = $_POST['date'] . ' ' . $_POST['time'].':00';
                if ( $page['created'] !== $created ) {
                    $terminator = date('Y-m-d H:i:s');
                    if ( $page['created'] < $terminator && $terminator <= $created ) {
                        $update_list = true;
                    }
                    if ( $created < $terminator && $terminator <= $page['created'] ) {
                        $update_list = true;
                    }
                }
                $tpl       = $_POST['template'];
                $q = "UPDATE pages SET 
                        title='{$title}', 
                        seo_title='{$seo_title}', 
                        description='{$description}', 
                        sort={$sort}, 
                        created='{$created}', 
                        type='{$tpl}', 
                        pid={$pid},
                        {$update_url}
                      WHERE id={$id}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    // Создать кеш
                    cms_create_cache();
                    $r = array(
                        'info_text'  => __('Updated', 'pages.mod.php'),
                        'info_class' => 'info-success',
                        'info_time'  => 1000,
                        'title'      => htmlspecialchars( $_POST['title'] ),
                        'short_url'  => $_POST['url'],
                        'new_url'    => $new_url,
                    );
                    if ( $update_list ) {
                        $r['list']    = cms_pages_get_pages_list();
                        $r['parents'] = cms_pages_get_parents_list();
                    }
                    if ( function_exists( "cms_sitemap_update" ) ) {
                        cms_sitemap_update();
                    }
                    exit ( json_encode( $r ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Error update properties', 'pages.mod.php').mysqli_error( $cms['base'] ),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;

            case 'save_page':
                $cms['status'] = '200';
                if ( empty( $_POST['id'] ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Empty page id', 'pages.mod.php'),
                        'info_class' => 'info-error',
                        'info_time'  => 3000,
                    ) ) );
                }
                if ( $_POST['text'] === NULL ) {
                    exit( json_encode( array(
                        'info_text' => 'NULL text error. Line: '.__LINE__,
                        'info_class' => 'info-error',
                        'info_time'  => 20000,
                    ) ) );
                }
                // hook for save page
                cms_do_stage('save_page');
                
                $id           = (int) $_POST['id'];
                $old_modified = str_replace(',', '.', (float)$_POST['modified']);
                $modified     = str_replace(',', '.', microtime(true));
                $text         = mysqli_real_escape_string( $cms['base'], $_POST['text'] );
                $q = "UPDATE pages SET text='{$text}', modified={$modified} WHERE id={$id} AND modified={$old_modified}";
                if ( mysqli_query( $cms['base'], $q ) ) {
                    if ( !mysqli_affected_rows( $cms['base'] ) ) {
                        exit( json_encode( array(
                            'info_text' => __('Someone already changed the page', 'pages.mod.php'),
                            'info_class' => 'info-error',
                            'info_time'  => 5000,
                        ) ) );
                    }

                    # Удалить старую страницу
                    if ( substr( $_POST['url'], -1, 1 ) === '/' ) {
                        $old_dir  = $cms['site_dir'] . $_POST['url'];
                        $old_file = $cms['site_dir'] . $_POST['url'] . 'index.html';
                    } else {
                        $old_dir  = '';
                        $old_file = $cms['site_dir'] . $_POST['url'];
                    }
                    if ( file_exists( $old_file ) ) {
                        unlink($old_file);
                    }
                    if ( is_dir( $old_dir ) ) {
                        rmdir( $old_dir );
                    }
                    if ( function_exists( "cms_sitemap_update" ) ) {
                        cms_sitemap_update();
                    }
                    exit( json_encode( array(
                        'info_text'  => __("Saved", "pages.mod.php"),
                        'info_class' => 'info-success',
                        'info_time'  => 3000,
                        'modified'   => $modified,
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Query error. Line:', 'pages.mod.php').__LINE__.__(' Query:', 'pages.mod.php').$q,
                        'info_class' => 'info-error',
                        'info_time'  => 0,
                    ) ) );
                }
            break;

            case 'get_page':
                $cms['status'] = '200';
                if ( $id = (int)$_POST['id'] and $res = mysqli_query( $cms['base'], "SELECT * FROM pages WHERE id={$id}" ) ) {
                    if ( $page = mysqli_fetch_assoc( $res ) ) {
                        /* Файлы страницы */
                        $farr = array();
                        foreach (glob($cms['site_dir'].'/uploads/'.$page['id'].'/*', GLOB_NOSORT) as $path) {
                            $farr[] = array( 'path' => $path, 'sort' => filemtime($path) );
                        }
                        cms_asort( $farr );
                        $flist = '';
                        foreach ( $farr as $f ) {
                            $path_name = str_replace($cms['site_dir'], '', $f['path']);
                            $ext = strtolower(preg_replace('/.*\./', '.', $path_name));
                            /* Выбираем иконку по расширению */
                            if ( file_exists( "{$cms['cms_dir']}/img/icon{$ext}.svg" ) ) {
                                $icon = "/img/icon{$ext}.svg";
                            } else {
                                $icon = "/img/icon.default.svg";
                            }
                            /* Для картинок иконка не нужна */
                            switch ($ext) {
                                case '.webp':
                                case '.tiff':
                                case '.jpeg':
                                case '.jpg':
                                case '.png':
                                case '.svg':
                                case '.gif':
                                case '.bmp':
                                case '.ico':
                                    $size = getimagesize( $cms['site_dir'].$path_name );
                                    if ( !empty( $size[3] ) ) {
                                        $size = $size[3];
                                    } else {
                                        $size = "";
                                    }
                                    $flist = "<div class='filesblocks'><img src='{$path_name}' data-src='{$path_name}' {$size}><label class='check option'><input class=check__input type=checkbox><span class=check__box></span></label><div class=ext>{$ext}</div></div>{$flist}";
                                break;
                                
                                default:
                                    $flist = "<div class='filesblocks'><img src='{$icon}' data-src='{$path_name}'><label class='check option'><input class=check__input type=checkbox><span class=check__box></span></label><div class=ext>{$ext}</div></div>{$flist}";
                                break;
                            }
                        }
                        /* Возвращаем страницу и список файлов страницы */
                        echo json_encode( array(
                            'result' => 'ok',
                            'page'   => $page,
                            'flist'  => $flist,
                        ) );
                    } else {
                        echo json_encode( array( 'result' => 'false' ) );
                    }
                }
            break;

            case 'del_files':
                foreach ($_POST['flist'] as $path_name) {
                    $f = $cms['site_dir'].$path_name;
                    if ( is_file( $f ) ) {
                        unlink( $f );
                    }
                }
                @rmdir(dirname($f));
                exit( json_encode( array(
                    'info_text'  => __("Files deleted", "pages.mod.php"),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'get_pages_list':
                $cms['status'] = '200';
                exit( json_encode( array(
                    'list'    => cms_pages_get_pages_list(),
                    'parents' => cms_pages_get_parents_list(),
                ) ) );
            break;

            case 'del_page':
                $cms['status'] = '200';
                if ( $id = (int) $_POST['id'] ) {
                    /* Удалить весь кеш */
                    cms_clear_cache();

                    if ( $res = mysqli_query( $cms['base'], "SELECT pid FROM pages WHERE id=$id" ) and $page = mysqli_fetch_assoc($res) ) {

                        /* Определить URL родительской */
                        if ( $page['pid'] ) {
                            $q = "SELECT url FROM pages WHERE id='{$page['pid']}'";
                            if ( $r = mysqli_query( $cms['base'], $q ) ) {
                                $parent = mysqli_fetch_assoc( $r );
                            }
                        } else {
                            $parent['url'] = $cms['base_path'];
                        }
                        
                        /* Изменить родителя и URL у дочерних */
                        cms_pages_update_childs_url( $id, $parent['url'] );
                        mysqli_query( $cms['base'], "UPDATE pages SET pid={$page['pid']} WHERE pid={$id}" );

                        /* Удалить страницу из базы */
                        mysqli_query( $cms['base'], "DELETE FROM pages WHERE id={$id}" );

                        /* Удалить файлы страницы */
                        foreach (glob($cms['site_dir'].'/uploads/'.$id.'/*', GLOB_NOSORT) as $f) {
                            if ( is_file( $f ) ) {
                                unlink( $f );
                            }
                        }
                        @rmdir(dirname($f));

                        /* Создать кеш */
                        cms_create_cache();
                        exit( json_encode( array(
                            'info_text'  => __("Page deleted", "pages.mod.php"),
                            'info_class' => 'info-success',
                            'info_time'  => 1000,
                            'list'       => cms_pages_get_pages_list(),
                            'parents'    => cms_pages_get_parents_list(),
                        ) ) );

                    } else {
                        exit( json_encode( array(
                            'info_text'  => __("Error delete page: ", "pages.mod.php") . mysqli_error( $cms['base'] ),
                            'info_class' => 'info-error',
                            'info_time'  => 5000,
                        ) ) );
                    }
                } else {
                    exit( json_encode( array(
                        'info_text'  => __("Error delete page: bad id", "pages.mod.php"),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;

            case 'recreate_cache':
                $cms['status'] = '200';
                cms_clear_cache();
                cms_create_cache();
                exit( json_encode( array(
                    'info_text'  => __('Pages Updated', 'pages.mod.php'),
                    'info_class' => 'info-success',
                    'info_time'  => 1000,
                ) ) );
            break;

            case 'upload_files':
                $id   = (int)$_POST['id'];
                $path = '/uploads/'.$id;
                $dir  = $cms['site_dir'].$path;
                /* Создание папки если не существует */
                if ( !is_dir( $dir ) && !mkdir( $dir, 0777, true ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Can\'t create folder','pages.mod.php').' '.$dir,
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
                $flist = '';
                $success = true;
                foreach ( $_FILES['myfile']['name'] as $n => $name ) {
                    if ( $_FILES['myfile']['error'][$n] ) {
                        $success = false;
                        $text = __('Error upload file','pages.mod.php').' '.$name;
                        break;
                    }
                    $ext = strtolower(preg_replace('/.*\./', '.', $name));
                    $name = substr($name, 0, strlen($name)-strlen($ext));
                    $name = strtolower( cms_translit_file( $name ) );
                    $name = "{$name}{$ext}";
                    $success = $success && move_uploaded_file( $_FILES['myfile']['tmp_name'][$n], "{$dir}/{$name}" );
                    if ( file_exists( "{$cms['cms_dir']}/img/icon{$ext}.svg" ) ) {
                        $icon = "/img/icon{$ext}.svg";
                    } else {
                        $icon = "/img/icon.default.svg";
                    }
                    if ( $success ) {
                        switch ($ext) {
                            case '.webp':
                            case '.tiff':
                            case '.jpeg':
                            case '.jpg':
                            case '.png':
                            case '.svg':
                            case '.gif':
                            case '.bmp':
                            case '.ico':
                                $size = getimagesize( "{$cms['site_dir']}{$path}/{$name}" );
                                if ( !empty( $size[3] ) ) {
                                    $size = $size[3];
                                } else {
                                    $size = "";
                                }
                                $flist .= "<div class='filesblocks active-file'><img src='{$path}/{$name}' data-src='{$path}/{$name}' data-type=img {$size}><label class='check option'><input class=check__input type=checkbox><span class=check__box></span></label><div class=ext>{$ext}</div></div>";
                            break;
                            
                            default:
                                $flist .= "<div class='filesblocks active-file'><img src='{$icon}' data-src='{$path}/{$name}' data-type=file><label class='check option'><input class=check__input type=checkbox><span class=check__box></span></label><div class=ext>{$ext}</div></div>";
                            break;
                        }
                        
                    }
                }

                if ( $success ) {
                    $text = __('Files uploaded','pages.mod.php');
                    exit( json_encode( array(
                        'info_text'  => $text,
                        'info_class' => 'info-success',
                        'info_time'  => 5000,
                        'flist'      => $flist,
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => $text,
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;
        }
    }
}

# Возвращает список <option> для выбора родительской страницы
function cms_pages_get_parents_list( $pid = 0, $lvl = 0 ) {
    global $cms;
    $pref = str_repeat("&emsp;&emsp;", $lvl);
    $parents = '';
    if ( empty( $cms['base'] ) ) {
        return "";
    }
    if ( $res = mysqli_query( $cms['base'], "SELECT id, pid, title, url FROM pages WHERE pid='{$pid}' ORDER BY title" ) ) {
        while ( $page = mysqli_fetch_assoc( $res ) ) {
            $title = htmlspecialchars( $page['title'] );
            $parents .= "<option value='{$page['id']}' data-url='{$page['url']}'>{$pref}{$title}</option>";
            $parents .= cms_pages_get_parents_list( $page['id'], $lvl+1 );
        }
    }
    return $parents;
}

# Возвращает список <option> для выбора подшаблона из текущего шаблона
function cms_pages_get_templates_list() {
    global $cms;
    $templates = '';
    $expr = $cms['cms_dir'] . '/' . $cms['config']['template.mod.php']['template'] . '/html-*.php';
    foreach ( glob( $expr ) as $tpl ) {
        $name = preg_replace( '/.+\/html-(.+)\.php/', '$1', $tpl );
        $templates .= "<option value='{$name}'>{$name}</option>";
    }
    return $templates;
}

# Создает иерархический список страниц для админки
function cms_pages_get_pages_list( $pid = 0 ) {
    global $cms;
    $templates = cms_pages_get_templates_list();
    $list = '';
    if ( empty( $cms['base'] ) ) {
        return "";
    }
    $q = "SELECT id, pid, title, seo_title, description, created, type_url, short_url, url, type, sort 
          FROM pages WHERE pid={$pid} ORDER BY sort, title";
    if ( ! $res = mysqli_query( $cms['base'], $q ) ) {
        return mysqli_error($cms['base']);
    } else {
        while ( $page = mysqli_fetch_assoc( $res ) ) {
            if ( $page['created'] === '0000-00-00 00:00:00' ) {
                $created = __("no date", 'pages.mod.php');
                $date    = '';
                $time    = '';
                $published = 'Published';
                $class = 'zero';
            } else {
                $time = strtotime( $page['created'] );
                if ( time() >= $time ) {
                    $published = 'Published';
                    $class     = 'published';
                } else {
                    $published = 'Planned';
                    $class     = 'planned';
                }
                $created = date( 'd.m.Y H:i', $time );
                $date    = date( 'Y-m-d', $time );
                $time    = date( 'H:i', $time );
            }
            if ( $page['type_url'] === 'auto' ) {
                $url = $page['short_url'];
            } elseif ( $page['type_url'] === 'manual' ) {
                $url = $page['url'];
            }
            $list   .= "
                <div class='pages-box' data-page-box>
                    
                    <div class='hotsetting' data-page-prop={$page['id']}>
                        <h1>".__("PAGE PROPERTIES", 'pages.mod.php')."</h1>
                        <div class='sett-grid-container'>
                        
                            <div class='Sett-LeftGrid'>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Title', 'pages.mod.php').":</div>
                                    <div><input data-page-id={$page['id']} name='title' type='text' class='settingx' value='{$page['title']}'></div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Label / URL', 'pages.mod.php').":</div>
                                    <div><input data-page-id={$page['id']} name='url' type='text' class='settingx' value='{$url}' data-page-url-type='{$page['type_url']}'></div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('SEO Title', 'pages.mod.php').":</div>
                                    <div><input data-page-id={$page['id']} name='seo_title' type='text' class='settingx' value='{$page['seo_title']}'></div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Description', 'pages.mod.php').":</div>
                                    <div><textarea data-page-id={$page['id']} name='description' class='settingx' rows='2'>{$page['description']}</textarea></div>
                                </div>
                            </div>
                        
                            <div class='Sett-RightGrid'>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Parent', 'pages.mod.php').":</div>
                                    <div class=select2-wrapper>
                                        <select data-page-parent={$page['pid']} class='settingx-right parents-list' data-page-id={$page['id']} name=pid>
                                            <option value='0'>".__('No parent', 'pages.mod.php')."</option>
                                        </select>
                                    </div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Template', 'pages.mod.php').":</div>
                                    <div class=select2-wrapper>
                                        <select class='settingx-right templates-list' data-page-template='{$page['type']}' data-page-id={$page['id']} name=template>
                                            <option value=''>".__('No template', 'pages.mod.php')."</option>
                                            {$templates}
                                        </select>
                                    </div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Sort', 'pages.mod.php').":</div>
                                    <div><input data-page-id={$page['id']} name='sort' type='text' class='settingx-right-order' value='{$page['sort']}'></div>
                                </div>
                                <div class='sett-attribute'>
                                    <div class='settinput-text'>".__('Date', 'pages.mod.php').":</div>
                                    <div>
                                        <input data-page-id={$page['id']} name='date' type='date' class='settingx-date' value='{$date}'>
                                        <input data-page-id={$page['id']} name='time' type='time' class='settingx-time' value='{$time}'>
                                    </div>
                                </div>
                            </div>
                        
                        </div>
                        
                        <div class='hotbott'>
                            <a href=# data-page-prop-cancel={$page['id']} class='button-close'>".__('Cancel', 'pages.mod.php')."</a>
                            <a href=# data-page-prop-save={$page['id']} class='button-save'>".__('Save', 'pages.mod.php')."</a>
                        </div>
                
                    </div>

                    <div data-page-item={$page['id']} class='cpline style-page'>

                        <div class=page-name>
                            <h1><a data-page-item-link={$page['id']} href='{$page['url']}' target=_blank title='id={$page['id']}'>{$page['title']}</a></h1>
                        </div>

                        <div class='page-buttons'>
                            <div class='admin-pagesetting'>
                                <div class='page-name-mobile'><div class=title>{$page['title']}</div><div class=close></div></div>
                                <a href=# class=edit-page data-page-edit-btn={$page['id']}>".__('Edit', 'pages.mod.php')."</a> 
                                <a href=# class=open-prop data-page-prop-open={$page['id']}>".__('Properties', 'pages.mod.php')."</a> 
                                <span class='a-red'><a data-page-del={$page['id']} href=# class=del-page>".__('Delete', 'pages.mod.php')."</a></span> 
                                <a href=# class=create-page data-page-create='{$page['pid']}' data-page-sort='{$page['sort']}'>".__('Add Page', 'pages.mod.php')."</a>
                                <a href=# class=create-page data-page-create='{$page['id']}'>".__('Add Child Page', 'pages.mod.php')."</a>
                            </div>
                        </div>

                        <div class=page-data>
                            <div class='admin-datapublicline {$class}'>".__($published, 'pages.mod.php')."<br>{$created}</div>
                        </div>

                        <div class=page-mobile data-page-menu='{$page['id']}'>
                        </div>

                        <!--
                        <div class=page-check>
                        <div class='admin-checkpageline'>
                            <input type=checkbox id='checkbox-id-{$page['id']}' name='checked[]' value='1'>
                            <label for=checkbox-id-{$page['id']} class=checkbox></label>
                        </div>
                        </div>
                        -->

                    </div>";
                    if ( $sublist = cms_pages_get_pages_list( $page['id'] ) ) {
                        $list .= "
                            <div class=subbox-grid>
                                {$sublist}
                            </div>
                        ";
                    }
            $list .= "
                </div>
            ";
        }
    }
    $list = preg_replace( '/(\s)+/', '$1', $list );
    return $list;
}


function cms_pages_query() {
    global $cms;
    
    // Skip SQL query if file exists
    if ( is_file( $cms['cms_file'] ) ) return;
    
    if (empty($cms['base'])) return;
    if (mysqli_connect_error()) return;
    $url = mysqli_real_escape_string($cms['base'], $cms['url']['path']);
    if ($res = mysqli_query($cms['base'], "SELECT * FROM pages WHERE url='$url'")) {
        if ($cms['page'] = mysqli_fetch_assoc($res)) {
            if ($cms['page']['created'] <= date('Y-m-d H:i:s')) {
                $cms['status'] = '200';
            } else {
                $cms['status'] = '404'; // disable write to disk
            }
            if ($cms['page']['pid'] !== 0
                and $res_parent = mysqli_query($cms['base'],"SELECT * FROM pages WHERE id='{$cms['page']['pid']}'")
                and $parent = mysqli_fetch_assoc($res_parent))
            {
                    $cms['page']['parent'] = $parent;
            }
        }
    }
}

function cms_pages_create_tables() {
    global $cms;
    if (!$res = mysqli_query($cms['base'], "SELECT * FROM pages")) {
        $first_run = true;
    } else {
        $first_run = false;
    }

    mysqli_query($cms['base'], "
    CREATE TABLE `pages` (
        `id` bigint(20) UNSIGNED NOT NULL,
        `pid` int(11) NOT NULL DEFAULT 0,
        `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
        `modified` double NOT NULL DEFAULT 0,
        `type` varchar(64) DEFAULT NULL,
        `title` varchar(255) DEFAULT NULL,
        `seo_title` varchar(255) DEFAULT NULL,
        `text` longtext DEFAULT NULL,
        `type_url` varchar(8) NOT NULL DEFAULT 'auto',
        `short_url` varchar(255) NOT NULL DEFAULT '',
        `url` varchar(255) DEFAULT NULL,
        `keywords` varchar(1024) NOT NULL DEFAULT '',
        `description` varchar(2048) NOT NULL DEFAULT '',
        `sort` int(11) NOT NULL DEFAULT 0
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
    mysqli_query($cms['base'], "ALTER TABLE `pages` ADD UNIQUE KEY `id` (`id`);");
    mysqli_query($cms['base'], "ALTER TABLE `pages` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;");

    // Create Demo Page
    if ( $first_run ) {
        $page = <<<EOP
<img class="banner" alt="Баннер" src="/uploads/banner.jpg" width="1920" height="700">


<div class="blog padding-normal">
    <h1>Заголовок записи</h1>
        <p>Это облёгчённый шаблон, созданный для творчества, одновременно является примером и отправной точкой для Вашего проекта.</p>
    <p>Перед началом использования рекомендуем ознакомиться с документацией по кастомизации тем и шаблонов.</p>
        <p>Ниже пример картинки выходящей за ширину текста и описанием за счёт добавления класса wide-picture тегу figure.</p>
    <figure class="wide-picture">
        <img alt="" src="/uploads/test.png" width="800" height="600">
        <figcaption>Описание изображения</figcaption>
    </figure>
    <p>Ниже пример картинки по ширине текста</p>
        <img alt="" src="/uploads/test.png" width="800" height="600">
        <p>Ниже пример картинки картинки выходящей за ширину текста за счёт добавления ей класса wide-picture</p>
        <img class="wide-picture" alt="" src="/uploads/test.png" width="800" height="600">
</div>
EOP;
        $page = mysqli_real_escape_string( $cms['base'], $page );
        mysqli_query($cms['base'], "INSERT INTO `pages` (`id`, `pid`, `created`, `modified`, `type`, `title`, `seo_title`, `text`, `type_url`, `short_url`, `url`, `keywords`, `description`, `sort`) VALUES
        (1, 0, '2020-04-13 21:40:00', 1587157038.9078, 'page', 'Mini (Demo)', '', '{$page}', 'auto', '/', '/', '', '', 0);");
    }
}

function cms_pages_admin() {
    global $cms;
    if (!is_admin()) return;
    $tr_upload_files = __("Upload files","pages.mod.php");
    $files_panel = "

    <div class='files-options-container hidden' data-page-editor-files>
		<div class='files-container'>
			<div class='files-container-grid' data-files-container>
				
			</div>
		</div>
		
		<div class='options-files-container'>
			<div class='options-container'>
                <div class='add-files'>
                <form data-upload-form action='{$cms['config']['admin.mod.php']['api_url']}' method=post>
                    <input type=hidden name=fn value=upload_files>
                    <input type=hidden name=id>
                    <input id=upload-btn type=file name='myfile[]' multiple class=inputfile>
                    <label title='{$tr_upload_files}' for='upload-btn'></label>
                </form>
                </div>
                <div class='link-file'>
                    <span class='link-file-tag' data-link-file></span>
                    <span class='link-file-copy-btn' data-link-file-copy>".__("Copy","pages.mod.php")."</span>
                </div>
				<div class='close-files' data-page-editor-files-close>".__("Close Mediateka","pages.mod.php")."</div>
				<div class='group-options-files disabled' data-media-del>".__("Delete files","pages.mod.php")."</div>
			</div>
		</div>
		
	</div>

    ";
    $buttons = "<div class='grid-button media' data-page-editor-files-btn>".__("Mediateka", "pages.mod.php")."</div>";
    $page = "
    <div class=main-header></div>
    <div class=main-main>
        <div class=toppanell>
            <div class='search-wrapper'>
                <input data-page-search class=page-search type=text placeholder='".__('Search...', 'pages.mod.php')."'>
                <button class=page-search-button type=submit></button>
            </div>
            <div class=groupmaster-check>
                <input type=checkbox id=0 value=0>
                <!--
                <label title='".__('Select all', 'pages.mod.php')."' for=0 class=checkbox></label>
                -->
            </div>
        </div>

        <div class=wrapper-page-grid data-pages-list>
            <!-- Pages -->
        </div>

        <div class=bottompanell>
            <a class='add-button add-page' href=# data-page-create=0>".__('Add page', 'pages.mod.php')."</a>
        </div>

        <!-- Page editor -->
        <div data-page-editor class='Bg-Page-Editor-Box hidden'>
            <div class=Page-Editor-Box>
                <div class=page-editor-grid>
                <div class=Header-Page>
                    <h1><a data-page-title href=# target=_blank id=coffee_page_title>".__('Title', 'pages.mod.php')."</a></h1>
                </div>
                <div class=Settings-Editor>
                    <div class=progress><div class=bar></div></div>
                    <!-- Кнопки для редактора -->
                    {$files_panel}
                    <div class=grid-buttons data-page-editor-buttons>{$buttons}</div>
                </div>
                <div class=Page-Editor>
                    <textarea data-page-text placeholder=Code class=coffee-editorpage-area id=coffee_editorpage-area name=add_editorpage>".__('Text', 'pages.mod.php')."</textarea>
                </div>
                <div class=Button-Box-Page>
                    <div class=hotbott-page-editor>
                    <a data-page-cancel-btn href=# class=button-close>".__('Close', 'pages.mod.php')."</a>
                    <a data-page-save-btn href=# class='button-save save'>".__('Save', 'pages.mod.php')."</a>
                    <a data-page-save-close-btn href=# class='button-save close'>".__('Save and Close', 'pages.mod.php')."</a>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>
    <div class=main-footer></div>";

    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['pages.mod.php']['menu']['pages'] ) ) {
        $cms['config']['pages.mod.php']['menu']['pages'] = array(
            'title'    => 'Pages',
            'sort'     => 20,
            'class'    => '',
            'section'  => 'Navigation',
        );
        cms_save_config();
    }

    $cms['admin_pages']['pages'] = $page;
}

function cms_pages_update_childs_url( $pid, $base_url ) {
    global $cms;
    $update_list = false;
    
    $q = "SELECT id, short_url, url, title FROM pages WHERE pid=$pid AND type_url='auto'";
    if ( $r = mysqli_query( $cms['base'], $q ) ) {
        while ( $child = mysqli_fetch_assoc( $r ) ) {
            if ( empty( $child['short_url'] ) ) {
                $child['short_url'] = strtolower( cms_translit( $child['title'] ) );
            }
            $child_url = $base_url . $child['short_url'] . '/';
            $update_list = $update_list || ( $child_url !== $child['url'] );
            $esc_child_url = mysqli_real_escape_string( $cms['base'], $child_url );
            mysqli_query( $cms['base'], "UPDATE pages SET url='{$esc_child_url}' WHERE id={$child['id']}" );
            // Update childs recursive
            $update_list = cms_pages_update_childs_url( $child['id'], $child_url ) || $update_list;
        }
    }
    
    return $update_list;
    
}
