<?php

/**
 * Administration panel - Extra fields editor for structure part
 *
 * @package Cotonti
 * @copyright (c) Cotonti Team
 * @license https://github.com/Cotonti/Cotonti/blob/master/License.txt
 */
(defined('COT_CODE') && defined('COT_ADMIN')) or die('Wrong URL.');

list(Cot::$usr['auth_read'], Cot::$usr['auth_write'], Cot::$usr['isadmin']) = cot_auth('admin', 'a');
cot_block(Cot::$usr['isadmin']);

require_once cot_incfile('extrafields');

$extra_blacklist = [
	$db_auth,
	$db_cache,
	$db_cache_bindings,
	$db_core,
	$db_updates,
	$db_online,
	$db_extra_fields,
	$db_config,
	$db_plugins
];
$extra_whitelist = [
	$db_structure => [
		'name' => $db_structure,
		'caption' => Cot::$L['Categories'],
		'type' => 'system',
		'code' => 'structure',
        'icon' => '<img src="' . Cot::$cfg['icons_dir'] . '/' . Cot::$cfg['defaulticons']
            . '/32/folder.png" alt="{PHP.L.Structure}" />',
		'tags' => [
			'page.list.tpl' => '{LIST_CAT_ROW_XXXXX}, {LIST_CAT_XXXXX}',
			'page.list.group.tpl' => '{LIST_CAT_ROW_XXXXX}, {LIST_CAT_XXXXX}',
			'page.tpl' => '{PAGE_CAT_XXXXX}, {PAGE_CAT_XXXXX_TITLE}',
			'admin.structure.inc.tpl' => '{ADMIN_STRUCTURE_XXXXX}, {ADMIN_STRUCTURE_XXXXX_TITLE},{ADMIN_STRUCTURE_FORMADD_XXXXX}, {ADMIN_STRUCTURE_FORMADD_XXXXX_TITLE}'
		]
	]
];
$adminPath[] = [cot_url('admin', 'm=other'), Cot::$L['Other']];
$adminPath[] = [cot_url('admin', 'm=extrafields'), Cot::$L['adm_extrafields']];
$adminTitle = Cot::$L['adm_extrafields'];
$maxperpage = (is_int(Cot::$cfg['maxrowsperpage']) && Cot::$cfg['maxrowsperpage'] > 0 || ctype_digit(Cot::$cfg['maxrowsperpage'])) ? Cot::$cfg['maxrowsperpage'] : 15;

$t = new XTemplate(cot_tplfile(['admin', 'extrafields', $n], 'core'));

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

if (empty($n) || in_array($n, $extra_blacklist)) {
	// no params
	$sql = $db->query("SHOW TABLES");
	$tablelist = [];
	while ($row = $sql->fetch()) {
		$table = current($row);
		if (!in_array($table, $extra_blacklist)) {
			if (cot_import('alltables', 'G', 'BOL')) {
				$tablelist[] = $table;
			} elseif(isset($extra_whitelist[$table])) {
				$tablelist[] = $table;
			}
		}
	}
	cot_import('alltables', 'G', 'BOL') && $adminPath[] = [cot_url('admin', 'm=extrafields&alltables=1'), Cot::$L['adm_extrafields_all']];
	$ii = 0;
	foreach ($tablelist as $table) {
		$name = '';
		$ext_info = [];
		$type = null;
        $icon = $extra_whitelist[$table]['icon'] ?? null;
		if (isset($extra_whitelist[$table])) {
            if (isset($extra_whitelist[$table]['type'])) {
                $type = $extra_whitelist[$table]['type'];
            }
            if ($type == 'module' || $type == 'plug') {
                $ext_info = cot_get_extensionparams($extra_whitelist[$table]['code'], $extra_whitelist[$table]['type'] == 'module');
                $name = $ext_info['name'];
                if (!empty($ext_info['icon'])) {
                    $icon = $ext_info['icon'];
                }
            }
            $name = (empty($name)) ? $extra_whitelist[$table]['caption'] : $name;
        }

        if ($icon === null) {
            $fileNames = [
                Cot::$cfg['icons_dir'] . '/' . Cot::$cfg['defaulticons'] . '/default.png',
                Cot::$cfg['icons_dir'] . '/default/default.png',
            ];
            foreach ($fileNames as $fileName) {
                if (file_exists($fileName)) {
                    $icon = cot_rc('img_none', ['src' => $fileName]);
                }
            }
        }

		$ii++;
		$t->assign([
			'ADMIN_EXTRAFIELDS_ROW_ICON' => $icon ?? '',
			'ADMIN_EXTRAFIELDS_ROW_ITEMNAME' => $name,
			'ADMIN_EXTRAFIELDS_ROW_TABLENAME' => $table . ((isset($extra_whitelist[$table])) ? " - " . $extra_whitelist[$table]['caption'] : ''),
			'ADMIN_EXTRAFIELDS_ROW_TABLE' => $table,
			'ADMIN_EXTRAFIELDS_ROW_TYPE' => $type,
			'ADMIN_EXTRAFIELDS_ROW_TABLEURL' => cot_url('admin', 'm=extrafields&n='.$table),
			'ADMIN_EXTRAFIELDS_COUNTER_ROW' => $ii,
			'ADMIN_EXTRAFIELDS_ODDEVEN' => cot_build_oddeven($ii)
		]);
		$t->parse('MAIN.TABLELIST.ROW');
	}
	$t->assign('ADMIN_EXTRAFIELDS_ALLTABLES', cot_url('admin', 'm=extrafields&alltables=1'));

	/* === Hook  === */
	foreach (cot_getextplugins('admin.extrafields.tablelist.tags') as $pl) {
		include $pl;
	}
	/* ===== */

	$t->parse('MAIN.TABLELIST');
} else {
	$a = cot_import('a', 'G', 'ALP');
	$id = (int) cot_import('id', 'G', 'INT');
	$name = cot_import('name', 'G', 'ALP');
	list($pg, $d, $durl) = cot_import_pagenav('d', $maxperpage);
	$parse_type = ['HTML', 'Text'];

	$adminPath[] = [cot_url('admin', 'm=extrafields&n='.$n), Cot::$L['adm_extrafields_table'] . ' '
        . $n . ((isset($extra_whitelist[$n])) ? ' - ' . $extra_whitelist[$n]['caption'] : '')];

    $redirectUrl = cot_url('admin', ['m' => 'extrafields', 'n' => $n, 'd' => $durl,], '', true);

	if ($a == 'add' && !empty($_POST)) {
		$field['field_name'] = cot_import('field_name', 'P', 'TXT');
		$field['field_type'] = cot_import('field_type', 'P', 'ALP');
		$field['field_html'] = cot_import('field_html', 'P', 'NOC');
		$field['field_variants'] = cot_import('field_variants', 'P', 'HTM');
		$field['field_params'] = cot_import('field_params', 'P', 'HTM');
		$field['field_description'] = cot_import('field_description', 'P', 'NOC');
		$field['field_default'] = cot_import('field_default', 'P', 'HTM');
		$field['field_required'] = cot_import('field_required', 'P', 'BOL');
		$field['field_parse'] = cot_import('field_parse', 'P', 'ALP');
		$field['field_noalter'] = cot_import('field_noalter', 'P', 'BOL');
		$field['field_enabled'] = 1;

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

        if (empty($field['field_name'])) {
            cot_error(Cot::$L['adm_extrafield_error_name_missing']);
        } elseif (!preg_match('/^\d*[A-Za-z\d_]+$/', $field['field_name'])) {
            cot_error(Cot::$L['adm_extrafield_error_name']);
        }

        if (empty($field['field_type'])) {
            cot_error('adm_extrafield_not_added');
        }

        if (cot_error_found()) {
            cot_redirect($redirectUrl);
        }

        if (
            cot_extrafield_add(
                $n,
                $field['field_name'],
                $field['field_type'],
                $field['field_html'],
                $field['field_variants'],
                $field['field_default'],
                $field['field_required'],
                $field['field_parse'],
                $field['field_description'],
                $field['field_params'],
                $field['field_enabled'],
                $field['field_noalter']
            )
        ) {
            cot_message('adm_extrafield_added');
        } else {
            cot_error('adm_extrafield_not_added');
        }

        cot_redirect($redirectUrl);

    } elseif ($a == 'upd' && !empty($_POST)) {
		$field_name = cot_import('field_name', 'P', 'ARR');
		$field_type = cot_import('field_type', 'P', 'ARR');
		$field_html = cot_import('field_html', 'P', 'ARR');
		$field_variants = cot_import('field_variants', 'P', 'ARR');
		$field_params = cot_import('field_params', 'P', 'ARR');
		$field_description = cot_import('field_description', 'P', 'ARR');
		$field_default = cot_import('field_default', 'P', 'ARR');
		$field_required = cot_import('field_required', 'P', 'ARR');
		$field_parse = cot_import('field_parse', 'P', 'ARR');
		$field_enabled = cot_import('field_enabled', 'P', 'ARR');

		/* === Hook - Part1 : Set === */
		$extp = cot_getextplugins('admin.extrafields.update');
		/* ===== */
		if (is_array($field_name)) {
			foreach ($field_name as $k => $v) {
				$field['field_name'] = cot_import($field_name[$k], 'D', 'ALP');
				$field['field_type'] = cot_import($field_type[$k], 'D', 'ALP');
				$field['field_html'] = cot_import($field_html[$k], 'D', 'NOC');
				$field['field_variants'] = isset($field_variants[$k]) ? cot_import($field_variants[$k], 'D', 'HTM') : null;
				$field['field_params'] = isset($field_params[$k]) ? cot_import($field_params[$k], 'D', 'HTM') : null;
				$field['field_description'] = cot_import($field_description[$k], 'D', 'NOC');
				$field['field_default'] = isset($field_default[$k]) ? cot_import($field_default[$k], 'D', 'HTM') : null;
				$field['field_required'] = cot_import($field_required[$k], 'D', 'BOL');
				$field['field_parse'] = cot_import($field_parse[$k], 'D', 'ALP');
				$field['field_enabled'] = cot_import($field_enabled[$k], 'D', 'BOL');
				$field['field_location'] = $n;

				if (
                    !empty($field['field_name'])
                    && (
                        empty($cot_extrafields[$n][$field['field_name']])
                        || $field != $cot_extrafields[$n][$field['field_name']]
                    )
                    && !empty($field['field_type'])
                ) {
					/* === Hook - Part2 : Include === */
					foreach ($extp as $pl) {
						include $pl;
					}
					/* ===== */

					$fieldresult = cot_extrafield_update(
                        $n,
                        $k,
                        $field['field_name'],
                        $field['field_type'],
                        $field['field_html'],
                        $field['field_variants'],
                        $field['field_default'],
                        $field['field_required'],
                        $field['field_parse'],
                        $field['field_description'],
                        $field['field_params'],
                        $field['field_enabled']
                    );

					if ($fieldresult == 1) {
						cot_message(sprintf(Cot::$L['adm_extrafield_updated'], $k));
					} elseif (!$fieldresult) {
						cot_error(sprintf(Cot::$L['adm_extrafield_not_updated'], $k));
					}
				}
			}
		}

        cot_redirect($redirectUrl);
	} elseif ($a == 'del' && isset($name)) {
		/* === Hook === */
		foreach (cot_getextplugins('admin.extrafields.delete') as $pl) {
			include $pl;
		}
		/* ===== */

		if (cot_extrafield_remove($n, $name)) {
			cot_message('adm_extrafield_removed');
		} else {
			cot_error('adm_extrafield_not_removed');
		}
        cot_redirect($redirectUrl);
	}

	cot_load_extrafields(true);

	$totalitems = Cot::$db->query("SELECT COUNT(*) FROM $db_extra_fields WHERE field_location = '$n'")->fetchColumn();
	$res = Cot::$db->query("SELECT * FROM $db_extra_fields WHERE field_location = '$n' ORDER BY field_name ASC LIMIT $d, ".$maxperpage);

	$pagenav = cot_pagenav('admin', 'm=extrafields&n='.$n, $d, $totalitems, $maxperpage, 'd', '', Cot::$cfg['jquery'] && Cot::$cfg['turnajax']);

	$field_types = [
		'input',
		'inputint',
		'currency',
		'double',
		'textarea',
		'select',
		'checkbox',
		'radio',
		'datetime',
		'country',
		'range',
		'checklistbox',
		'file'/* ,
		'filesize' */
	];

	$ii = 0;
	/* === Hook - Part1 : Set === */
	$extp = cot_getextplugins('admin.extrafields.loop');
	/* ===== */
    $cols = 55;
	foreach ($res->fetchAll() as $row) {
		$ii++;

        $deleteUrl = cot_url('admin', ['m' => 'extrafields', 'n' => $n, 'a' => 'del', 'name' => $row['field_name']]);
        $deleteConfirmUrl = cot_confirm_url($deleteUrl, 'admin');

		$t->assign([
			'ADMIN_EXTRAFIELDS_ROW_NAME' => cot_inputbox('text', 'field_name['.$row['field_name'].']', $row['field_name'], 'class="exfldname"'),
			'ADMIN_EXTRAFIELDS_ROW_FIELDNAME' => htmlspecialchars($row['field_name']),
			'ADMIN_EXTRAFIELDS_ROW_DESCRIPTION' => cot_textarea(
                'field_description[' . $row['field_name'] . ']',
                $row['field_description'],
                1,
                $cols,
                'class="exflddesc"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_SELECT' => cot_selectbox($row['field_type'], 'field_type['.$row['field_name'].']', $field_types, $field_types, false, 'class="exfldtype"'),
			'ADMIN_EXTRAFIELDS_ROW_VARIANTS' => cot_textarea(
                'field_variants[' . $row['field_name'] . ']',
                $row['field_variants'],
                1,
                $cols,
                'class="exfldvariants"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_PARAMS' => cot_textarea(
                'field_params[' . $row['field_name'] . ']',
                $row['field_params'],
                1,
                $cols,
                'class="exfldparams"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_HTML' => cot_textarea(
                'field_html[' . $row['field_name'] . ']',
                $row['field_html'],
                1,
                $cols,
                'class="exfldhtml"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_DEFAULT' => cot_textarea(
                'field_default[' . $row['field_name'] . ']',
                $row['field_default'],
                1,
                $cols,
                'class="exflddefault"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_REQUIRED' => cot_checkbox(
                $row['field_required'],
                'field_required[' . $row['field_name'] . ']',
                Cot::$L['adm_extrafield_required'],
                'class="exfldrequired"'
            ),
			'ADMIN_EXTRAFIELDS_ROW_ENABLED' => cot_checkbox($row['field_enabled'], 'field_enabled['.$row['field_name'].']', '', 'title="'.Cot::$L['adm_extrafield_enable'].'" class="exfldenabled" '),
			'ADMIN_EXTRAFIELDS_ROW_PARSE' => cot_selectbox($row['field_parse'], 'field_parse['.$row['field_name'].']', $parse_type, [Cot::$L['Default'], Cot::$L['No']], false, 'class="exfldparse"'),
			'ADMIN_EXTRAFIELDS_ROW_BIGNAME' => strtoupper($row['field_name']),
			'ADMIN_EXTRAFIELDS_ROW_ID' => $row['field_name'],
			'ADMIN_EXTRAFIELDS_ROW_DEL_URL' => $deleteUrl,
            'ADMIN_EXTRAFIELDS_ROW_DELETE_CONFIRM_URL' => $deleteConfirmUrl,
			'ADMIN_EXTRAFIELDS_ROW_COUNTER_ROW' => $ii,
			'ADMIN_EXTRAFIELDS_ROW_ODDEVEN' => cot_build_oddeven($ii)
		]);

		/* === Hook - Part2 : Include === */
		foreach ($extp as $pl) {
			include $pl;
		}
		/* ===== */

		$t->parse('MAIN.TABLE.EXTRAFIELDS_ROW');
	}

	$tags_list = '';
	$tags_list_li = '';
	if (isset($extra_whitelist[$n])) {
        if (is_array($extra_whitelist[$n]['tags'])) {
            foreach ($extra_whitelist[$n]['tags'] as $ktags => $vtags) {
                $tags_list .= cot_rc('admin_exflds_array', ['tplfile' => $ktags, 'tags' => $vtags]);
                $tags_list_li .= '<li>' . cot_rc('admin_exflds_array', ['tplfile' => $ktags, 'tags' => $vtags]) . '</li>';
            }
        }
    }

	$t->assign([
		'ADMIN_EXTRAFIELDS_URL_FORM_EDIT' => cot_url('admin', 'm=extrafields&n='.$n.'&a=upd&d='.$durl),
		'ADMIN_EXTRAFIELDS_NAME' => cot_inputbox('text', 'field_name', '', 'class="exfldname"'),
		'ADMIN_EXTRAFIELDS_DESCRIPTION' => cot_textarea('field_description', '', 1, 30, 'class="exflddesc"'),
		'ADMIN_EXTRAFIELDS_SELECT' => cot_selectbox('input', 'field_type', $field_types, $field_types, false, 'class="exfldtype"'),
		'ADMIN_EXTRAFIELDS_VARIANTS' => cot_textarea('field_variants', '', 1, 60, 'class="exfldvariants"'),
		'ADMIN_EXTRAFIELDS_PARAMS' => cot_textarea('field_params', '', 1, 60, 'class="exfldparams"'),
		'ADMIN_EXTRAFIELDS_HTML' => cot_textarea('field_html', '', 1, 60, 'class="exfldhtml"'),
		'ADMIN_EXTRAFIELDS_DEFAULT' => cot_textarea('field_default', '', 1, 60, 'class="exflddefault"'),
		'ADMIN_EXTRAFIELDS_REQUIRED' => cot_checkbox(
            0,
            'field_required',
            Cot::$L['adm_extrafield_required'],
            'class="exfldrequired"'
        ),
		'ADMIN_EXTRAFIELDS_PARSE' => cot_selectbox('HTML', 'field_parse', $parse_type, [Cot::$L['Default'], Cot::$L['No']], false, 'class="exfldparse"'),
		'ADMIN_EXTRAFIELDS_URL_FORM_ADD' => cot_url('admin', 'm=extrafields&n='.$n.'&a=add&d='.$durl),
		'ADMIN_EXTRAFIELDS_PAGINATION_PREV' => $pagenav['prev'],
		'ADMIN_EXTRAFIELDS_PAGNAV' => $pagenav['main'],
		'ADMIN_EXTRAFIELDS_PAGINATION_NEXT' => $pagenav['next'],
        'ADMIN_EXTRAFIELDS_ON_PAGE_ITEMS' => $pagenav['onpage'],
		'ADMIN_EXTRAFIELDS_TOTALITEMS' => $totalitems,
		'ADMIN_EXTRAFIELDS_TAGS' => $tags_list
	]);

	cot_display_messages($t);

	if (isset($extra_whitelist[$n]['help'])) {
		$adminHelp = $extra_whitelist[$n]['help'];
	} else {
		$adminHelp = Cot::$L['adm_help_info'];
		if (!empty($tags_list)) {
			$adminHelp .= Cot::$L['adm_help_newtags'].'<ul class="follow">'.$tags_list_li.'</ul>';
		}
	}

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

	$t->parse('MAIN.TABLE');
}
$t->parse('MAIN');
$adminMain = $t->text('MAIN');