<?php

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

class Categories {

    private $data = array();
    private $parent = array();
    private $nchi = array();
    private $chi = array();
    private $arr = array();
    private $last_path = array();

    public function __construct($area) {
        $this->area = $area;
        global $structure, $cfg, $db_structure, $db, $sys, $R;
        $sql = $db->query("SELECT * FROM $db_structure WHERE structure_area='" . $db->prep($area) . "' ORDER BY structure_path ASC, structure_code ASC");
        $totalitems = $db->query("SELECT COUNT(*) FROM $db_structure WHERE structure_area='" . $db->prep($area) . "'")->fetchColumn();
        foreach ($sql->fetchAll() as $row) {
            $this->data[$row['structure_id']] = $row;
            $this->arr[$row['structure_path']] = $row['structure_id'];
            $parent = $this->last_parent($row['structure_path']);
            $this->parent[$row['structure_path']] = $parent;
            if ($parent != null) {
                $this->chi[$parent][] = $row['structure_id'];
            } else {
                $this->nchi[] = $row['structure_id'];
            }
            preg_match('/^((.+)\.)?(.+)$/i', $row['structure_path'], $mt);
            $mt[3];
            $this->last_path[$row['structure_id']] = $mt[3];
        }
    }

    private function last_parent($path) {
        preg_match('/^(.+)\.(.+)$/i', $path, $mt_curr);
        if (empty($mt_curr[1])) {
            return null;
        } elseif (isset($this->arr[$mt_curr[1]])) {
            return $this->arr[$mt_curr[1]];
        }
        return $this->last_parent($mt_curr[1]);
    }

    public function nested_patch($category) {
        return $this->data[$category]['structure_path'];
    }

    public function last_path($parent = null) {
        $last_path = array();
        $array = array();
        $array = (empty($parent)) ? $this->nchi : $this->chi[$parent];
        if (empty($array)) {
            return "001";
        }
        foreach ($array as $id) {
            $last_path[] = $this->last_path[$id];
        }
        $max = max($last_path);
        $max++;

        $lenght = mb_strlen($max);

        $max = str_pad((int) $max++, 3, "0", STR_PAD_LEFT);
        return str_pad($max, $lenght, "0", STR_PAD_LEFT);
    }

    public function newpath($parent = null) {
        $position = $this->last_path($parent);
        if (empty($parent)) {
            return $position;
        }
        return $this->data[$parent]['structure_path'] . '.' . $position;
    }

    public function clist($parent = null, $depth = 0, $tpl = 'eadmin.categories.list', $selectedid = null) {

        $array = array();
        $array = (empty($parent)) ? $this->nchi : $this->chi[$parent];

        $is_module = cot_module_active($this->area);

        if (empty($array)) {
            return false;
        } else {
            $t = new XTemplate(cot_tplfile($tpl, 'module'));
            foreach ($array as $id) {
                $jj++;
                $row = $this->data[$id];
                $n = $row['structure_area'];
                $resolute = ($row['structure_count'] > 0) ? false : true;
                $t->assign(array(
                    'ADMIN_STRUCTURE_DEL_URL' => $resolute ? cot_confirm_url(cot_url('eadmin', 'em=categories&n=' . $n . '&a=delete&id=' . $row['structure_id'] . '&' . cot_xg()), 'admin') : '',
                    'ADMIN_STRUCTURE_EDIT_URL' => cot_url('eadmin', 'em=categories&n=' . $this->area . '&id=' . $row['structure_id']),
                    'ADMIN_STRUCTURE_RIGHTS_URL' => $is_module ? cot_url('admin', 'm=rightsbyitem&ic=' . $this->area . '&io=' . $row['structure_code']) : '',
                    'ADMIN_STRUCTURE_OPEN_URL' => cot_url($n, 'c=' . $row['structure_code']),
                    'ADMIN_STRUCTURE_ID' => $row['structure_id'],
                    'ADMIN_STRUCTURE_CODE' => $row['structure_code'],
                    'ADMIN_STRUCTURE_TITLE' => $row['structure_title'],
                    'ADMIN_STRUCTURE_DESC' => $row['structure_desc'],
                    'ADMIN_STRUCTURE_SELECTED' => $row['structure_id'] == $selectedid ? 1 : 0,
                    'ADMIN_STRUCTURE_ICON' => $row['structure_icon'],
                    'ADMIN_STRUCTURE_CHILDREN' => $this->clist($row['structure_id'], $depth + 1, $tpl),
                    'ADMIN_STRUCTURE_COUNT' => $row['structure_count']
                ));
                $t->parse("MAIN.CATS.ROW");
            }
            $t->parse("MAIN.CATS");
            if (empty($parent)) {
                $t->parse("MAIN");
                return $t->text("MAIN");
            }
            return $t->text("MAIN.CATS");
        }
    }

    public function parent_cat($chosen, $name, $add_empty = true, $attrs = '') {
        require_once cot_incfile('forms');
        $values = array();
        foreach ($this->data as $id => $row) {
            $values[$id] = $this->sosub($row['structure_path']) . $row['structure_title'];
        }
        return cot_selectbox($chosen, $name, array_keys($values), array_values($values), $add_empty, $attrs);
    }

    private function sosub($data) {
        $count = mb_substr_count($data, '.');
        $substr = '';
        for ($i = 0; $i < $count - 1; $i++) {
            $substr .= "° ";
        }
        if ($count > 0) {
            $substr .="° ";
        }
        return $substr;
    }

    function cat_code($title, $id = 0) {
        global $cfg, $cot_translit, $cot_translit_custom;

        if (file_exists(cot_langfile('translit', 'core'))) {
            include cot_langfile('translit', 'core');
            if (is_array($cot_translit_custom)) {
                $title = strtr($title, $cot_translit_custom);
            } elseif (is_array($cot_translit)) {
                $title = strtr($title, $cot_translit);
            }
        }
        $title = preg_replace('#[^\p{L}0-9\-_ ]#u', '', $title);
        $title = str_replace(' ', '-', $title);
        $title = mb_strtolower($title);

        $duplicate = false;
        foreach ($this->data as $d_id => $d_cat) {
            if ($id != $d_id && $title == $d_cat['structure_code']) {
                $duplicate = true;
            }
        }
        if ($duplicate) {
            if (!empty($id)) {
                $title .= '-' . $id;
            } else {
                $title .= '-' . rand(2, 99);
            }
        }

        return $title;
    }

    public function category($id) {
        if (!empty($this->data[$id])) {
            return $this->data[$id];
        }
        return false;
    }

    public function edit($id, $n, $tpl = 'edit') {
        require_once cot_incfile($n, 'module');
        global $cot_modules, $cot_extrafields, $db_structure, $structure, $L, $R;

        $cats_class = new Categories($n);
        $row = $cats_class->category($id);
        if (empty($row)) {
            return null;
        }

        cot::$out['title'] = $L['EA_admin_catmanage'];
        cot::$out['small_title'] = $cot_modules[$n]['title'];

        cot::$out['adminpath'][] = array(cot_url('eadmin', 'em=categories'), $L['EA_admin_cats']);
        cot::$out['adminpath'][] = array(cot_url('eadmin', 'em=categories&n=' . $n), $cot_modules[$n]['title']);
        cot::$out['adminpath'][] = $L['Edit'];

        $ii++;
        $structure_id = $row['structure_id'];
        $structure_code = $row['structure_code'];
        $n = $row['structure_area'];
        $is_module = cot_module_active($n);

        $t = new XTemplate(cot_tplfile('eadmin.categories.' . $tpl, 'module'));

        $t->assign(array(
            'ADMIN_STRUCTURE_HEADER' => $row['structure_title'],
            'ADMIN_STRUCTURE_UPDATE_FORM_URL' => cot_url('eadmin', 'em=categories&n=' . $n . '&id=' . $structure_id . '&a=update'),
            'ADMIN_STRUCTURE_ID' => $row['structure_id'],
            'ADMIN_STRUCTURE_CODE' => cot_inputbox('text', 'rstructurecode', $structure_code, 'class="form-control" maxlength="255"'),
            'ADMIN_STRUCTURE_PATH' => cot_inputbox('hidden', 'rstructurepath', $row['structure_path']),
            'ADMIN_STRUCTURE_TPL' => cot_inputbox('text', 'rstructuretpl', $row['structure_tpl'], 'class="form-control" maxlength="255"'),
            'ADMIN_STRUCTURE_TITLE' => cot_inputbox('text', 'rstructuretitle', $row['structure_title'], 'class="form-control" maxlength="255"'),
            'ADMIN_STRUCTURE_DESC' => cot_inputbox('text', 'rstructuredesc', $row['structure_desc'], 'class="form-control" maxlength="255"'),
            'ADMIN_STRUCTURE_ICON' => cot_inputbox('text', 'rstructureicon', $row['structure_icon'], 'class="form-control" maxlength="128"'),
            'ADMIN_STRUCTURE_LOCKED' => cot_checkbox($row['structure_locked'], 'rstructurelocked'),
            'ADMIN_STRUCTURE_COUNT' => $row['structure_count'],
            'ADMIN_STRUCTURE_RIGHTS_URL' => $is_module ? cot_url('admin', 'm=rightsbyitem&ic=' . $n . '&io=' . $structure_code) : '',
        ));

        foreach ($cot_extrafields[$db_structure] as $exfld) {
            $exfld_val = cot_build_extrafields('rstructure' . $exfld['field_name'], $exfld, $row['structure_' . $exfld['field_name']]);
            $exfld_title = isset($L['structure_' . $exfld['field_name'] . '_title']) ? $L['structure_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
            $t->assign(array(
                'ADMIN_STRUCTURE_' . strtoupper($exfld['field_name']) => $exfld_val,
                'ADMIN_STRUCTURE_' . strtoupper($exfld['field_name']) . '_TITLE' => $exfld_title,
                'ADMIN_STRUCTURE_EXTRAFLD' => $exfld_val,
                'ADMIN_STRUCTURE_EXTRAFLD_TITLE' => $exfld_title
            ));
            $t->parse('MAIN.EXTRAFLD');
        }


        require_once cot_incfile('configuration');
        $optionslist = cot_config_list($is_module ? 'module' : 'plug', $n, $structure_code);

        /* === Hook - Part1 : Set === */
        $extp = cot_getextplugins('admin.config.edit.loop');
        /* ===== */
        foreach ($optionslist as $row_c) {
            list($title, $hint) = cot_config_titles($row_c['config_name'], $row_c['config_text']);

            if ($row_c['config_type'] == COT_CONFIG_TYPE_SEPARATOR) {
                $t->assign('ADMIN_CONFIG_FIELDSET_TITLE', $title);
                $t->parse('MAIN.OPTIONS.CONFIG.ADMIN_CONFIG_ROW.ADMIN_CONFIG_FIELDSET_BEGIN');
            } else {
                $t->assign(array(
                    'ADMIN_CONFIG_ROW_CONFIG' => cot_config_input($row_c),
                    'ADMIN_CONFIG_ROW_CONFIG_TITLE' => $title,
                    'ADMIN_CONFIG_ROW_CONFIG_MORE_URL' => cot_url('admin', 'm=structure&n=' . $n . '&d=' . $durl . '&id=' . $structure_id . '&al=' . $structure_code . '&a=reset&v=' . $row_c['config_name'] . '&' . cot_xg()),
                    'ADMIN_CONFIG_ROW_CONFIG_MORE' => $hint
                ));
                /* === Hook - Part2 : Include === */
                foreach ($extp as $pl) {
                    include $pl;
                }
                /* ===== */
                $t->parse('MAIN.CONFIG.ADMIN_CONFIG_ROW.ADMIN_CONFIG_ROW_OPTION');
            }
            $t->parse('MAIN.CONFIG.ADMIN_CONFIG_ROW');
        }
        /* === Hook  === */
        foreach (cot_getextplugins('admin.config.edit.tags') as $pl) {
            include $pl;
        }
        /* ===== */
        $t->assign('CONFIG_HIDDEN', cot_inputbox('hidden', 'editconfig', $structure_code));
        $t->parse('MAIN.CONFIG');

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

    public function reorder($array, $path = null) {
        $return = array();
        $count = count($array);
        $lenght = mb_strlen($count);

        $i = 000;
        foreach ($array as $key => $val) {
            $i = str_pad((int) ++$i, 3, "0", STR_PAD_LEFT);
            $pos = str_pad($i, $lenght, "0", STR_PAD_LEFT);
            if (!empty($path)) {
                $pos = $path . "." . $pos;
            }
            $return[$val['id']] = $pos;
            if (!empty($val['children'])) {
                $rtemp = $this->reorder($val['children'], $pos);
                $return = $return + $rtemp;
            }
        }
        return $return;
    }

}