<?php

/**
 * EasyAdmin for Giglance
 *
 * @package Eadmin Main Class
 * @version 2.6.9
 * @author CoTEMPLATE
 * @copyright Copyright (c) CoTEMPLATE.com
 */
(defined('COT_CODE') && defined('COT_ADMIN')) or die('Wrong URL.');

class MainMod {

    public function categoriesAction() {
        global $cfg, $L, $cot_auth_default_lock, $cot_auth_default_permit;
        cot::$out['subtitle'] = $L['EA_admin_catmanage'] . ' - ' . cot::$L['Administration'];
        $n = cot_import('n', 'G', 'TXT');
        $a = cot_import('a', 'G', 'TXT');
        $id = cot_import('id', 'G', 'INT');
        require_once cot_incfile('eadmin', 'module', 'categories');

        /* === Hook === */
        foreach (cot_getextplugins('admin.structure.first') as $pl) {
            include $pl;
        }
        /* ===== */

        if (is_array($extension_structure) && count($extension_structure) == 1 && ((cot_plugin_active($extension_structure[0]) || cot_module_active($extension_structure[0])))) {
            $n = $extension_structure[0];
        }


        if (!empty($n)) {
            $cats_class = new Categories($n);
            $is_module = (cot_module_active($n));

            if (file_exists(cot_incfile($n, $is_module ? 'module' : 'plug'))) {
                require_once cot_incfile($n, $is_module ? 'module' : 'plug');
            }
            require_once cot_incfile('structure');
        }
        if ($a == 'add' && !empty($_POST)) {
            require_once cot_incfile('eadmin', 'module', 'categories.add');
        } elseif ($a == 'update' && !empty($_POST)) {
            require_once cot_incfile('eadmin', 'module', 'categories.update');
        } elseif ($a == 'delete') {
            cot_check_xg();
            $scode = $cats_class->category($id);
            $c = $scode['structure_code'];
            if (cot_structure_delete($n, $c, $is_module)) {
                /* === Hook === */
                foreach (cot_getextplugins('admin.structure.delete.done') as $pl) {
                    include $pl;
                }
                /* ===== */
                cot_message('Deleted');
            }

            cot_redirect(cot_url('eadmin', 'em=categories&n=' . $n, '', true));
        } elseif ($a == 'sync') {
            cot_check_xg();
            global $db, $db_structure, $cache;
            $res = false;
            $area_sync = 'cot_' . $n . '_sync';
            if (function_exists($area_sync)) {
                $res = true;
                $sql = $db->query("SELECT structure_code FROM $db_structure WHERE structure_area='" . $db->prep($n) . "'");
                foreach ($sql->fetchAll() as $row) {
                    $cat = $row['structure_code'];
                    $items = $area_sync($cat);
                    $db->update($db_structure, array("structure_count" => (int) $items), "structure_code='" . $db->prep($cat) . "' AND structure_area='" . $db->prep($n) . "'");
                }
                $sql->closeCursor();
            }

            /* === Hook === */
            foreach (cot_getextplugins('admin.structure.resync.done') as $pl) {
                include $pl;
            }
            /* ===== */

            $res ? cot_message('Resynced') : cot_message("Error: function $area_sync doesn't exist."); // TODO i18n
            ($cache && $cfg['cache_' . $n]) && $cache->page->clear($n);
            cot_redirect(cot_url('eadmin', 'em=categories&n=' . $n, '', true));
        }

        require_once cot_incfile('eadmin', 'module', 'categories.editor');
        return $t->text('MAIN');
    }

    public function usersAction() {
		global $usr, $db, $cot_extrafields, $cot_groups, $cot_countries, $cache, $db_stats, $db_users, $db_groups_users, $db_pages, $db_forum_topics,
        $db_forum_posts, $db_pm, $L, $sys, $cfg, $db_logger, $db_referers, $db_trash, $db_com, $db_projects;

		cot::$out['subtitle'] = $L['EA_Users_manage'] . ' - ' . $L['Administration'];
        cot::$out['title'] = $L['EA_Users_manage'];

        cot::$out['adminpath'][] = $L['Users'];
        cot::$out['adminpath'][] = $L['EA_manage'];

        list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('eadmin', 'any', 'RWA');
        cot_block($usr['auth_read']);

        require_once cot_incfile('users', 'module');
        //require_once cot_incfile('pm', 'module');
        require_once cot_langfile('eadmin', 'module');
        require_once cot_incfile('eadmin', 'module');

        $temp = new XTemplate(cot_tplfile(array('eadmin', 'users'), 'module'));

        $protected = $sys['protecttopadmin'] ? array('disabled' => 'disabled') : array();
        $editor_class = $cfg['users']['usertextimg'] ? 'minieditor' : '';

        $id = cot_import('id', 'G', 'INT');
        $sort = cot_import('sort', 'G', 'ALP', 16);
        $w = cot_import('w', 'G', 'ALP', 4);

        list($pg, $d, $durl) = cot_import_pagenav('d', $cfg['users']['maxusersperpage']);

        if (empty($sort) || in_array(mb_strtolower($sort), $users_sort_blacklist) || !in_array($sort, $users_sort_whitelist) && !$db->fieldExists($db_users, "user_$sort")) {
            $sort = 'regdate';
        }
        if (!in_array($w, array('asc', 'desc'))) {
            $w = 'desc';
        }
        if (empty($f)) {
            $f = 'all';
        }
        if (empty($d)) {
            $d = 0;
        }

        $where['1'] = "1";

        switch ($sort) {
            case 'grplevel':
                $sqlorder = "g.grp_level $w";
                break;
            case 'grpname':
                $sqlorder = "g.grp_name $w";
                break;
            default:
                $sqlorder = "user_$sort $w";
                break;
        }

        $users_url_path = array('em' => 'users');

        $totalusers = $db->query("SELECT COUNT(*) FROM $db_users AS u $join_condition WHERE " . implode(" AND ", $where))->fetchColumn();

        if ($totalusers > 0 && $d > $totalusers) {
            cot_die_message(404);
        }

        $sqlusers = $db->query("SELECT u.* $join_columns FROM $db_users AS u $join_condition 
		WHERE " . implode(" AND ", $where) . " ORDER BY $sqlorder LIMIT $d,{$cfg['users']['maxusersperpage']}")->fetchAll();

        $totalpage = ceil($totalusers / $cfg['users']['maxusersperpage']);
        $currentpage = ceil($d / $cfg['users']['maxusersperpage']) + 1;
        $pagenav = cot_pagenav('eadmin', $users_url_path, $d, $totalusers, $cfg['users']['maxusersperpage'], 'd', '');

        $sql = $db->query("SELECT * FROM $db_users");
        $rowcount = $sql->rowCount();
        cot_die($rowcount == 0);

        $jj = 0;

        foreach ($sqlusers as $urr) {
            $jj++;
            $temp->assign(array(
                'USER_ROW_ODDEVEN' => cot_build_oddeven($jj),
                'USER_ROW_NUM' => $jj,
                'USER_ROW' => $urr
            ));
            $temp->assign(cot_generate_ea_usertags($urr, 'USER_ROW_'));
            $temp->parse('MAIN.USERS_LIST.USER_ROWS');
        }


        $temp->assign(array(
            'USERS_TOP_PAGNAV' => $pagenav['main'],
            'USERS_TOP_PAGEPREV' => $pagenav['prev'],
            'USERS_TOP_PAGENEXT' => $pagenav['next'],
        ));
        $temp->parse('MAIN.USERS_LIST.USERS_PAGENAV');
        $temp->parse('MAIN.USERS_LIST');

        cot_display_messages($temp);

        $temp->parse('MAIN');
        return $temp->text('MAIN');
    }

    public function structureAjax() {
        global $L;
        require_once cot_incfile('eadmin', 'module', 'categories');
        require_once cot_incfile('eadmin', 'module', 'functions');

        $n = cot_import('n', 'R', 'TXT');
        $id = cot_import('id', 'R', 'INT');
        $a = cot_import('a', 'R', 'TXT');
        $t = cot_import('t', 'R', 'TXT');

        if (is_array($extension_structure) && count($extension_structure) == 1 && ((cot_plugin_active($extension_structure[0]) || cot_module_active($extension_structure[0])))) {
            $n = $extension_structure[0];
        }

        $status = array();
        if (!empty($n)) {
            $cats_class = new Categories($n);
            $is_module = (cot_module_active($n));
            if (file_exists(cot_langfile('page', 'module'))) {
                require_once cot_langfile('page', 'module');
            }
            if (file_exists(cot_langfile('comments', 'plug'))) {
                require_once cot_langfile('comments', 'plug');
            }

            if (file_exists(cot_incfile($n, $is_module ? 'module' : 'plug'))) {
                require_once cot_incfile($n, $is_module ? 'module' : 'plug');
            }
        }
        if ($a == 'saveorder') {
            global $db, $db_structure;

            $data = cot_import('data', 'P', 'TXT');

            $catpathes = $cats_class->reorder(json_decode($data, true));
            $updated = 0;
            foreach ($catpathes as $id => $path) {
                if ($cats_class->nested_patch($id) != $path) {
                    $updated++;
                    $db->update($db_structure, array("structure_path" => $path), "structure_id='" . (int) $id . "'");
                }
            }
            if ($updated > 0) {
                $status = array('title' => $L['EA_notice'], 'status' => 'notice', 'message' => $L['EA_admin_order_new']);
            } else {
                $status = array('title' => $L['EA_notice'], 'status' => 'default', 'message' => $L['EA_admin_order_old']);
            }
        } elseif ($id > 0) {
            $status['content'] = $cats_class->edit($id, $n, 'edit_ajax');
        }


        if ($status['content']) {
            $status['content'] = preg_replace("@[\\r|\\n|\\t]+@", "", $status['content']);
        }
        cot_sendheaders('application/json');

        $status['id'] = (int) $id;
        $status['x'] = $sys['xk'];

        return json_encode($status);
        exit;
    }

}