<?php

$cms['modules']['menu.mod.php'] = array(
    'name' => __('Menu', 'menu.mod.php'),
    'description' => __('Module for building menu', 'menu.mod.php'),
    'url_title' => __('Module page'),
    'url_link' => __('https://coffee-cms.com/en/modules/menu/', 'menu.mod.php'),
    'author' => __('Coffee CMS team'),
    'version' => '20.07',
    'files' => array(
        '.cms/mod/menu.mod.php',
        '.cms/js/menu.js',
    ),
    'sort'    => 10,
);

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


cms_add_function('create_tables', 'cms_menu_create_table');
cms_add_function('admin',         'cms_menu_admin', 11);
cms_add_function('ajax',          'cms_menu_ajax', 11);


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

            case 'create_menu_item':
                $cms['status'] = '200';
                $pid = (int) $_POST['pid'];
                $q = "INSERT INTO menu SET pid={$pid}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    $mid = mysqli_insert_id( $cms['base'] );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Error creating: ', 'menu.mod.php') . mysqli_error( $cms['base'] ),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }

                // Create title, url and update
                if ( $pid ) {
                    $title = __('Menu item', 'menu.mod.php');
                } else {
                    $title = __('Menu', 'menu.mod.php');
                }
                $title     = mysqli_real_escape_string( $cms['base'], $title );
                $url       = mysqli_real_escape_string( $cms['base'], '/' );
                $url       = '';
                if (strlen($_POST['sort'])) {
                    if ($_POST['sort2']) {
                        $sort = (int)(( $_POST['sort'] + $_POST['sort2'] ) / 2);
                    } else {
                        $sort = $_POST['sort'] + 10;
                    }
                } else {
                    $sort      = $mid * 10;
                }
                $q = "UPDATE menu SET title='{$title}', url='{$url}', sort={$sort} WHERE mid={$mid}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    exit( json_encode( array(
                        'info_text'  => __('Created', 'menu.mod.php'),
                        'info_class' => 'info-success',
                        'info_time'  => 1000,
                        'list'       => cms_menu_get_items_list()[0],
                        'parents'    => cms_menu_get_parents_list(),
                        'pages'      => cms_pages_get_parents_list(),
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Error creating: ', 'menu.mod.php') . mysqli_error( $cms['base'] ),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;

            case 'get_menu_items':
                $cms['status'] = '200';
                exit( json_encode( array(
                    'list'       => cms_menu_get_items_list()[0],
                    'parents'    => cms_menu_get_parents_list(),
                    'pages'      => cms_pages_get_parents_list(),
                ) ) );
            break;

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

                    cms_menu_del( $mid );

                    // Создать кеш
                    cms_create_cache();
                    exit( json_encode( array(
                        'info_text'  => __('Deleted', 'menu.mod.php'),
                        'info_class' => 'info-success',
                        'info_time'  => 5000,
                        'list'       => cms_menu_get_items_list()[0],
                        'parents'    => cms_menu_get_parents_list(),
                        'pages'      => cms_pages_get_parents_list(),
                    ) ) );
                } else {
                    exit( json_encode( array(
                        'info_text'  => __('Delete error: bad id', 'menu.mod.php'),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }
            break;

            case 'save_menu_item':
                $cms['status'] = '200';
                cms_clear_cache();
                $mid       = (int) $_POST['mid'];
                $pid       = (int) $_POST['pid'];
                $id        = (int) $_POST['id'];
                $sort      = (int) $_POST['sort'];
                $title     = mysqli_real_escape_string( $cms['base'], $_POST['title'] );
                $tag_title = mysqli_real_escape_string( $cms['base'], $_POST['tag_title'] );
                $classes   = mysqli_real_escape_string( $cms['base'], $_POST['classes'] );
                $url       = mysqli_real_escape_string( $cms['base'], $_POST['url'] );
                $area      = mysqli_real_escape_string( $cms['base'], $_POST['area'] );
                if ( $_POST['target'] == 'true' ) {
                    $target_blank = 1;
                } else {
                    $target_blank = 0;
                }

                $q = "UPDATE menu SET
                        pid='{$pid}',
                        id='{$id}',
                        sort='{$sort}',
                        title='{$title}',
                        tag_title='{$tag_title}',
                        class='{$classes}',
                        url='{$url}',
                        area='{$area}',
                        target_blank='{$target_blank}'
                      WHERE mid={$mid}";
                if ( $r = mysqli_query( $cms['base'], $q ) ) {
                    // Создать кеш
                    cms_create_cache();
                    $r = array(
                        'info_text'  => __('Updated', 'menu.mod.php'),
                        'info_class' => 'info-success',
                        'info_time'  => 1000,
                        'list'       => cms_menu_get_items_list()[0],
                        'parents'    => cms_menu_get_parents_list(),
                        'pages'      => cms_pages_get_parents_list(),
                    );
                    exit ( json_encode( $r ) );
                } else {
                    $file = basename(__FILE__);
                    exit( json_encode( array(
                        'info_text'  => __('Error update properties', 'menu.mod.php').': '.$file.' '.__LINE__.': '.mysqli_error( $cms['base'] ),
                        'info_class' => 'info-error',
                        'info_time'  => 5000,
                    ) ) );
                }

            break;

        }
    }
}

function cms_menu_del( $mid ) {
    global $cms;

    // Считать свернутые меню
    if ( empty( $cms['cookie_menu'] ) ) {
        $cms['cookie_menu'] = json_decode($_COOKIE['menu']);
    }

    // Удалить дочерние пункты
    $q = "SELECT mid FROM menu WHERE pid={$mid}";
    if ( $res = mysqli_query( $cms['base'], $q ) ) {
        while ( $r = mysqli_fetch_assoc( $res ) ) {
            cms_menu_del( $r['mid'] );
        }
    }
    
    // Удалить пункт из базы
    mysqli_query( $cms['base'], "DELETE FROM menu WHERE mid=$mid" );

    // Удалить из кукисов
    $cms['cookie_menu'] = array_diff( $cms['cookie_menu'], array( $mid ) );
    setcookie( 'menu', json_encode( $cms['cookie_menu'] ) );
}

function cms_menu_get_items_list( $pid = 0 ) {
    global $cms;
    
    $areas = '';
    if ( isset( $cms['areas'] ) )
    foreach ( $cms['areas'] as $area => $a ) {
        $areas .= "<option value='{$area}'>{$a['title']}</option>";
    }

    $list = '';
    $q = "SELECT * FROM menu WHERE pid={$pid} ORDER BY sort, title";
    if ( !empty( $cms['base'] ) and $res = mysqli_query( $cms['base'], $q ) ) {
        $n = 0;
        while ( $item = mysqli_fetch_assoc( $res ) ) {
            $n++;

            // Вложенные пункты
            list( $sublist, $sn ) = cms_menu_get_items_list( $item['mid'] );
            if ( $sublist ) {
                $sublist = " <div class='subbox-grid open' data-menu-subitems={$item['mid']}> {$sublist} </div> ";
                $subitems = "<a href=# class=subitems-prop data-menu-subitems-hide={$item['mid']}>".__('Subitems', 'menu.mod.php').": {$sn}</a> ";
            } else {
                $subitems = "<a href=# class=subitems-prop data-menu-subitems-hide={$item['mid']}>".__('Subitems', 'menu.mod.php').": 0</a> ";
            }

            if ( $item['pid'] ) {
                // this is item
                $prop = __("ITEM PROPERTIES", 'menu.mod.php');
                $parent = "
                    <div class='sett-attribute prop-parent'>
                        <div class='settinput-text'>".__('Parent', 'menu.mod.php').":</div>
                        <div class=select2-wrapper>
                            <select data-menu-parent={$item['pid']} class='settingx-right parents-list' data-menu-id={$item['mid']} name=pid>
                                <option value='0'>".__('No parent', 'menu.mod.php')."</option>
                            </select>
                        </div>
                    </div>
                ";
                // Если свой заголовок пуст, подтянуть из страницы
                if ( empty( $item['title'] ) ) {
                    $q = "SELECT title FROM pages WHERE id='{$item['id']}'";
                    if ( $res_page = mysqli_query( $cms['base'], $q ) and $page = mysqli_fetch_assoc( $res_page ) ) {
                        $title = $page['title'];
                    }
                } else {
                    $title = $item['title'];
                }
                // Если есть URL то завернуть заголовок в него
                if ( $item['url'] ) {
                    $title = "<a href='{$item['url']}' target=_blank>{$title}</a>";
                } else {
                    $title = "{$title}";
                }
                $area   = "";
                $class = 'style-menu-item';
                $page = "
                    <div class='sett-attribute prop-page'>
                        <div class='settinput-text'>".__('Page', 'menu.mod.php').":</div>
                        <div class=select2-wrapper>
                            <select class='settingx-right pages-list' data-menu-page={$item['id']} name=id data-menu-id={$item['mid']}>
                                <option value='0'>".__('No page', 'menu.mod.php')."</option>
                            </select>
                        </div>
                    </div>
                ";
                $area = "";
                if ( $item['target_blank'] ) {
                    $target_blank = 'checked';
                } else {
                    $target_blank = '';
                }
                $url = "
                    <div class='sett-attribute prop-url'>
                        <div class='settinput-text'>".__('URL', 'menu.mod.php').":</div>
                        <div class='target-blank'>
                            <input data-menu-id={$item['mid']} name='url' type='text' class='settingx' value='{$item['url']}'>
                            <div title='Открывать в новом окне' class=target-blank-position>
                                <input data-menu-id={$item['mid']} id=menu-targetblank-{$item['mid']} type=checkbox name=targetblank {$target_blank}>
                                <label for=menu-targetblank-{$item['mid']} class=checkbox></label>
                            </div>
                        </div>
                    </div>
                ";
                $tag_title = "
                    <div class='sett-attribute prop-classes'>
                        <div class='settinput-text'>".__('Tag Title', 'menu.mod.php').":</div>
                        <div><input data-menu-id={$item['mid']} name='tag_title' type='text' class='settingx' value='{$item['tag_title']}'></div>
                    </div>
                ";
                $title_placeholder = __('Replaces page title', 'menu.mod.php');
                $title_area = "";
                $create_item = "<a href=# class=create-item data-menu-create='{$item['pid']}' data-menu-sort='{$item['sort']}'>".__('Create Item', 'menu.mod.php')."</a>";
                $create_subitem = "<a href=# class=create-item data-menu-create='{$item['mid']}'>".__('Sub Item', 'menu.mod.php')."</a>";
            } else {
                // this is menu
                $prop = __("MENU PROPERTIES", 'menu.mod.php');
                $parent = "";
                if ( $item['area'] ) {
                    if ( isset( $cms['areas'] ) && isset( $cms['areas'][ $item['area'] ] ) ) {
                        $title_area = $cms['areas'][ $item['area'] ]['title'];
                    } else {
                        $title_area = $item['area'];
                    }
                } else {
                    $title_area = __('No Area', 'menu.mod.php');
                }
                $title = "{$item['title']}";
                $title_area = "({$title_area})";
                $class = 'style-menu';
                $page = "";
                $area = "
                    <div class='sett-attribute prop-area'>
                        <div class='settinput-text'>".__('Area', 'menu.mod.php').":</div>
                        <div class=select2-wrapper>
                            <select class='settingx-right areas-list' data-menu-area='{$item['area']}' name=area data-menu-id={$item['mid']}>
                                <option value=''>".__('No Area', 'menu.mod.php')."</option>
                                {$areas}
                            </select>
                        </div>
                    </div>
                ";
                $url = "";
                $tag_title = "";
                $title_placeholder = "";
                $create_item = "<a href=# class=create-item data-menu-create='{$item['mid']}'>".__('Create Item', 'menu.mod.php')."</a>";
                $create_subitem = "";
            }
            
            $list   .= "
                <div class='pages-box' data-menu-box>
                    
                    <div class='hotsetting hidden' data-menu-prop={$item['mid']} data-pid={$item['pid']}>
                        <h1>".__($prop, 'menu.mod.php')."</h1>
                        <div class='sett-grid-container'>
                            <div class='Sett-LeftGrid'>
                                {$page}
                                {$area}
                                <div class='sett-attribute prop-title'>
                                    <div class='settinput-text'>".__('Title', 'menu.mod.php').":</div>
                                    <div><input data-menu-id={$item['mid']} name='title' type='text' class='settingx' value='{$item['title']}' placeholder='{$title_placeholder}'></div>
                                </div>
                                {$url}
                            </div>
                        
                            <div class='Sett-RightGrid'>
                                {$parent}
                                {$tag_title}
                                <div class=settsub-grid-container>
                                    <div class='settsub-left-grid settsub-attribute'>
                                        <div class=settinput-text>".__('Classes', 'menu.mod.php').":</div>
                                        <div><input data-menu-id={$item['mid']} name=classes type=text class=settingx value='{$item['class']}'></div>
                                    </div>
                                    <div class='settsub-right-grid settsub-attribute'>
                                        <div class=settinput-text>".__('Sort', 'menu.mod.php').":</div>
                                        <div><input data-menu-id={$item['mid']} name=sort type=text class=settingx-right-order value='{$item['sort']}'></div>
                                    </div>
                                </div>
                            </div>
                        
                        </div>
                        
                        <div class='hotbott'>
                            <a href=# data-menu-cancel={$item['mid']} class='button-close'>".__('Cancel', 'menu.mod.php')."</a>
                            <a href=# data-menu-save={$item['mid']} class='button-save'>".__('Save', 'menu.mod.php')."</a>
                        </div>
                
                    </div>

                    <div class='cpline {$class}' data-menu-item={$item['mid']}>
                        
                        <h1>{$title} {$title_area}</h1>
                        
                        <div class='admin-pagesetting'>
                            {$subitems}
                            <a href=# class=open-prop data-menu-prop-open={$item['mid']}>".__('Properties', 'menu.mod.php')."</a> 
                            <span class='a-red'><a href=# class=del data-menu-del={$item['mid']}>".__('Delete', 'menu.mod.php')."</a></span> 
                            {$create_item}
                            {$create_subitem}
                        </div>

                    </div>
                    {$sublist}
                </div>
            ";
        }
    } else return array( mysqli_error($cms['base']), -1 );
    $list = preg_replace( '/(\s)+/', '$1', $list );
    return array( $list, $n );
}

function cms_menu_get_parents_list( $pid = 0, $lvl = 0 ) {
    global $cms;
    $parents = '';
    if ( $res = mysqli_query( $cms['base'], "SELECT mid, pid, title, id FROM menu WHERE pid={$pid} ORDER BY sort" ) ) {
        while ( $item = mysqli_fetch_assoc( $res ) ) {
            if ( empty($item['title']) ) {
                $q = "SELECT title FROM pages WHERE id='{$item['id']}'";
                if ( $res_page = mysqli_query( $cms['base'], $q ) and $page = mysqli_fetch_assoc( $res_page ) ) {
                    $item['title'] = $page['title'];
                }
            }
            $title = htmlspecialchars( $item['title'] );
            $ident = str_repeat( '&emsp;', $lvl );
            $parents .= "<option value='{$item['mid']}'>{$ident}{$title} </option>";
            $parents .= cms_menu_get_parents_list( $item['mid'], $lvl+1 );
        }
    }
    $parents = preg_replace( '/(\s)+/', '$1', $parents );
    return $parents;
}

function cms_menu_admin() {
    global $cms;
    if (!is_admin()) return;
    $page = '
    <div class="wrapper-page-grid" data-menu-list>
        <!-- Menu Items -->
    </div>
    <div class=bottompanell>
        <a class="add-button add-menu" href=# data-menu-create=0>'.__('Add menu', 'menu.mod.php').'</a>
    </div>';
    // Создаем пункт меню, если еще не создан
    if ( empty( $cms['config']['menu.mod.php']['menu']['menu'] ) ) {
        $cms['config']['menu.mod.php']['menu']['menu'] = array(
            'title'    => 'Menu',
            'sort'     => 10,
            'class'    => '',
            'section'  => 'Navigation',
        );
        cms_save_config();
    }

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

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

    mysqli_query($cms['base'], "
    CREATE TABLE `menu` (
        `mid` bigint(20) UNSIGNED NOT NULL,
        `pid` int(11) DEFAULT 0,
        `id` int(11) NOT NULL DEFAULT 0,
        `title` varchar(255) NOT NULL DEFAULT '',
        `tag_title` varchar(255) NOT NULL DEFAULT '',
        `url` varchar(255) NOT NULL DEFAULT '',
        `sort` int(11) NOT NULL DEFAULT 1000,
        `class` varchar(255) NOT NULL DEFAULT '',
        `area` varchar(255) NOT NULL DEFAULT '',
        `target_blank` tinyint(1) NOT NULL DEFAULT 0
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    ");
    mysqli_query($cms['base'], "ALTER TABLE `menu` ADD UNIQUE KEY `mid` (`mid`);");
    mysqli_query($cms['base'], "ALTER TABLE `menu` MODIFY `mid` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;");
    
    // Create Demo Menus
    if ( $first_run ) {
        mysqli_query($cms['base'], "
        INSERT INTO `menu` (`mid`, `pid`, `id`, `title`, `tag_title`, `url`, `sort`, `class`, `area`, `target_blank`) VALUES
        (1, 0, 0, 'Меню над баннером', '', '', 10, 'navbar', 'header', 0),
        (2, 1, 1, 'Главная', '', '/', 20, '', '', 0),
        (3, 1, 0, 'Лицензия', '', '/License.txt', 30, '', '', 1),
        (4, 1, 0, 'Карта сайта', '', '/sitemap.xml', 40, '', '', 1),
        (5, 0, 0, 'Выезжающее меню', '', '', 50, 'mobimenu', 'mobile', 0),
        (6, 5, 1, 'Главная', '', '/', 60, '', '', 0),
        (7, 5, 0, 'Пункт 2', 'Фальшивая ссылка', '#', 70, '', '', 0),
        (8, 5, 0, 'Пункт 3', 'Фальшивая ссылка', '#', 80, '', '', 0),
        (9, 5, 0, 'Пункт 4', 'Фальшивая ссылка', '#', 90, '', '', 0),
        (10, 5, 0, 'Пункт 5', 'Фальшивая ссылка', '#', 100, '', '', 0);
        ");
    }
}

// Для того чтобы вывести несколько меню в одной области нужен отдельный цикл
function menu( $area ) {
    global $cms;
    $area = mysqli_real_escape_string( $cms['base'], $area );
    $q = "SELECT * FROM menu WHERE pid=0 AND area='{$area}' ORDER BY sort";
    $html = '';
    if ( $res = mysqli_query( $cms['base'], $q ) ) {
        while ( $menu = mysqli_fetch_assoc( $res ) ) {
            $html .= menu1( $menu['mid'] );
        }
    }
    return $html;
}

function menu1( $pid = 0 ) {
    global $cms;
    
    $q = "SELECT m.url as url, m.title as title, m.tag_title as tag_title, m.id as id, p.url as url2, p.title as title2, target_blank, m.mid as mid, m.class as class FROM menu m LEFT JOIN pages p ON m.id=p.id WHERE m.pid={$pid} ORDER BY m.sort";
    $html = '';
    if ( $res2 = mysqli_query( $cms['base'], $q ) ) {
        while ( $item = mysqli_fetch_assoc( $res2 ) ) {
            if ( $item['id'] ) {
                $item['url'] = $item['url2'];
                if ( empty( $item['title'] ) ) {
                    $item['title'] = $item['title2'];
                }
            }
            if ( $item['url'] === $cms['page']['url'] ) {
                $class = 'active';
            } else {
                $class = '';
            }
            if ( $item['target_blank'] ) {
                $target_blank = ' target=_blank';
            } else {
                $target_blank = '';
            }
            if ( $item['tag_title'] ) {
                $tag_title = " title='{$item['tag_title']}'";
            } else {
                $tag_title = '';
            }
            // submenu
            $sub = menu1( $item['mid'] );
            if ( !empty($sub) ) {
                $class .= " has-sub-menu";
            }
            if ( !empty( $class ) || !empty( $item['class'] ) ) {
                $class = "class='".trim("{$class} {$item['class']}")."'";
            }
            $html .= "<li {$class}><a href='{$item['url']}'{$target_blank}{$tag_title}>{$item['title']}</a>";
            $html .= $sub;
            $html .= "</li>";
        }
    }

    $q = "SELECT * FROM menu WHERE mid=$pid";
    if ( !empty( $html ) and $res = mysqli_query( $cms['base'], $q ) and $menu = mysqli_fetch_assoc( $res ) ) {
        if ( !empty( $menu['class'] ) && $menu['pid'] == 0 ) {
            $class = "class='{$menu['class']}'";
        } else {
            $class = "class='sub-menu'";
        }
        $html = "<ul {$class}>{$html}</ul>";
    }

    return $html;
}