<form method="post" enctype="multipart/form-data">
	<!-- Page header -->
    {include file="components/group-buttons.tpl" url="{$adminUrl}/typecontent?action=edit{if isset($typeId)}&id={$typeId}{/if}"}

    {capture name="breadcrumb"}
	    <a href="{$adminUrl}/typecontents" class="breadcrumb-item">Тип контента</a>
		<a href="{$adminUrl}/typecontent?action=edit{if isset($typeId)}&id={$typeId}{/if}" class="breadcrumb-item">{if isset($title)}{$title}{/if}</a>
{*		<span class="breadcrumb-item active">{general:add}</span>*}
    {/capture}

    {capture name="showBy"}{/capture}

    {include file="components/page-header.tpl" buttons=$smarty.capture.buttons breadcrumb=$smarty.capture.breadcrumb showBy=$smarty.capture.showBy}
	<!-- /page header -->

	<div class="content">

		<div class="row">
			<div class="col-md-12">
				<div class="card border shadow-sm">
					<div class="card-header d-flex flex-wrap p-0">
						<ul class="nav nav-tabs nav-tabs-overline border-top-0">
							<li class="nav-item">
								<a href="#general" class="nav-link active show" data-bs-toggle="tab" id="tab_general">{general:card:general}</a>
							</li>

							<li class="nav-item collapse {if isset($field.type) && ($field.type eq 'R' || $field.type eq 'S' || $field.type eq 'M')}show{/if}" id="tab_variants">
								<a href="#tabProperties" class="nav-link" data-bs-toggle="tab">Варианты</a></li>
						</ul>
					</div>
					<div class="card-body">
						<div class="tab-content border-top-0 rounded-top-0 mb-0">

							<div class="tab-pane fade show active" id="general">
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label {if isset($errors.name)}text-danger{/if}">Название поля:</label>
									<div class="col-lg-9">
										<input type="text" class="form-control" id="name" autocomplete="off" name="field[name]" value="{if isset($field.name)}{$field.name}{/if}">
									</div>
								</div>
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label {if isset($errors.fileName) || isset($errors.fileNameExists) || isset($errors.fileNameCharacters)}text-danger{/if}">Ключ поля:</label>
									<div class="col-lg-9">
										<input type="text" class="form-control" id="fileName" autocomplete="off" name="field[fileName]" value="{if isset($field.fileName)}{$field.fileName}{/if}">
										<div class="form-control form-control-plaintext fs-sm text-danger">
											<p>Последовательность символов, используемая в качестве идентификатора. Вы можете использовать цифры от 0 до 9, символы английского алфавита и знак "_".</p>
										</div>
									</div>
								</div>
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label">Тип:</label>
									<div class="col-lg-9">
										{* field status *}
										{include file="components/fields/select.tpl" col="col-md-4" id="typeFields" title="" field="field[type]" array=$typeFields selected=$field.type|default:'' class="form-group" width='300'}
										{* /field status *}
									</div>
								</div>
								<div class="row mb-3 radio_group_position collapse {if isset($field.type) && $field.type eq 'R'}show{/if}">
									<label class="col-lg-3 col-form-label">Расположение радиогруппы:</label>
									<div class="col-lg-9">
                                        {include file="components/fields/select.tpl" col="col-md-4" id="radio_group_position" title="" field="field[radio_group_position]" array=$radioGroupPositions selected=$field.radio_group_position|default:'' class="form-group" width='300'}
									</div>
								</div>

								<div class="row mb-3 radio_group_sql collapse {if isset($field.type) && $field.type eq 'R' || $field.type eq 'S' || $field.type eq 'C'}show{/if}">
									<label class="col-lg-3 col-form-label">SQL <br>VARCHAR( 255 ) NULL, <br> CHAR( 1 ) NOT NULL DEFAULT 0:</label>
									<div class="col-lg-9">
										<input type="text" class="form-control" id="type_sql" autocomplete="off" name="field[type_sql]" value="{if isset($field.type_sql)}{$field.type_sql}{/if}">
									</div>
								</div>


								<div class="row mb-3">
									<label class="col-lg-3 col-form-label {if isset($errors.typeId)}text-danger{/if}">Тип контента:</label>
									<div class="col-lg-9">
										{* field status *}
										{include file="components/fields/select.tpl" col="col-md-4" id="selectTypeContents" title="" field="field[typeId]" array=$selectTypeContents
		                                    selected="{if isset($typeId) && $typeId > 0}{$typeId}{else}{$field.typeId|default:''}{/if}" class="form-group" width='300'}
										{* /field status *}
									</div>
								</div>


								<div class="row mb-3">
									<label class="col-lg-3 col-form-label">Пользовательский CSS-класс:</label>
									<div class="col-lg-9">
										<input type="text" class="form-control" id="css" autocomplete="off" name="field[class]" value="{if isset($field.class)}{$field.class}{/if}">
									</div>
								</div>
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label">Пользовательский CSS-класс оболочки:</label>
									<div class="col-lg-9">
										<input type="text" class="form-control" id="css" autocomplete="off" name="field[wrapper_class]" value="{if isset($field.wrapper_class)}{$field.wrapper_class}{/if}">
									</div>
								</div>
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label">{general:status}:</label>
									<div class="col-lg-9">
	                                    {* field status *}
	                                    {include file="components/fields/select.tpl" col="col-md-4" id="status" title="" field="field[status]" array=$statuses selected=$field.status|default:'V' class="form-group" width='300'}
	                                    {* /field status *}
									</div>
								</div>
								<div class="row mb-3">
									<label class="col-lg-3 col-form-label">Раположение:</label>
									<div class="col-lg-9">
                                        {* field position *}
                                        {include file="components/fields/select.tpl" col="col-md-4" id="position" title="" field="field[position]" array=$positions selected=$field.position|default:'M' class="form-group" width='300'}
                                        {* /field position *}
									</div>
								</div>
							</div>

							<div class="tab-pane fade collapse{if isset($field.type) && ($field.type eq 'R' || $field.type eq 'S' || $field.type eq 'M')}show{/if}" id="tabProperties">
								<table class="table table-xs table-togglable table-striped table-hover">
									<thead>
										<tr>
											<th width="150">Ключ</th>
											<th>Значение</th>
											<th class="text-center text-muted" width="300"><i class="icon-checkmark3"></i></th>
										</tr>
									</thead>
									<tbody class="selectable-demo-list" id="properties">
									{foreach $properties as $property}
										<tr class="">
											<td class="text-start">
												<input type="hidden" class="form-control" name="field_data[{$property.propertyId}][propertyId]" value="{$property.propertyId}">
												<input type="text" class="form-control" name="field_data[{$property.propertyId}][propertyKey]" value="{$property.propertyKey}">
											</td>
											<td class="text-start">
												<input type="text" class="form-control" name="field_data[{$property.propertyId}][name]" value="{$property.name}">
											</td>
											<td class="text-end">
												<div class="input-group">
													<button type="button" class="btn btn-outline-primary add_property"><i class="ph-plus me-2"></i>{general:add}</button>
													<button type="button" class="btn btn-outline-primary del_variant"><i class="ph-trash me-2"></i> {general:delete}</button>
												</div>
											</td>
										</tr>
										{foreachelse}
										<tr class="">
											<td class="text-start">
												<input type="hidden" class="form-control" name="field_data[0][propertyId]">
												<input type="text" class="form-control" name="field_data[0][propertyKey]">
											</td>
											<td class="text-start">
												<input type="text" class="form-control" name="field_data[0][name]">
											</td>
											<td class="text-end">
												<div class="input-group">
													<button type="button" class="btn btn-outline-primary add_property"><i class="ph-plus me-2"></i>{general:add}</button>
													<button type="button" class="btn btn-outline-primary "><i class="ph-trash me-2"></i> {general:delete}</button>
												</div>
											</td>
										</tr>
									{/foreach}
									</tbody>
								</table>
							</div>

						</div>
					</div>

				</div>
			</div>

			<div class="col-md-12 text-center">
                {if isset($field.fieldId)}<input type="hidden" class="form-control" id="id" name="id" value="{$field.fieldId|default:''}">{/if}
                {$smarty.capture.buttons nofilter}
			</div>

		</div>
	</div>
</form>

{* Подключаем Tiny MCE *}
{include file='tinymce_init.tpl'}

<script>

    function notFound() {
        new Noty({ text: '{articles:errors:6}', layout: 'topRight', type: 'error', timeout: 1500 }).show();
    }
    function deleteMessage() {
        new Noty({ text: '{articles:messages:2}', type: 'success', timeout: 1500 }).show();
    }

    $(document).ready(function () {
        {if isset($messages.saved)} new Noty({ text: 'Новое поле "{if isset($field.name)}{$field.name}{/if}" сохранено', type: 'success', timeout: 1500 }).show(); {/if}

        {if isset($errors.name)} new Noty({ text: 'Введите название поля', type: 'error', timeout: 2500 }).show();{/if}
        {if isset($errors.not_saved)} new Noty({ text: 'Новое поле "{if isset($field.name)}{$field.name}{/if}" не сохранено', type: 'error', timeout: 2500 }).show(); {/if}

        {if isset($errors.fileName)} new Noty({ text: 'Введите ключ поля на анг. языке', type: 'error', timeout: 2500 }).show(); {/if}
        {if isset($errors.fileNameExists)} new Noty({ text: 'Ключ с этим названием уже сужествует', type: 'error', timeout: 2500 }).show(); {/if}
        {if isset($errors.fileNameCharacters)} new Noty({ text: 'Ключ может содержать только следующие символы: A-Z a-z _', type: 'error', timeout: 2500 }).show(); {/if}

        {if isset($errors.typeId)} new Noty({ text: 'Выберите тип контента', type: 'error', timeout: 2500 }).show(); {/if}
    });


    $(document).on('change', '#typeFields', function() {
        console.log($(this).val())
        if ($(this).val() == 'R' || $(this).val() == 'S') {
            $('#tab_variants').addClass('show')
            $('.radio_group_sql').addClass('show')

        } else {
            $('#tab_variants').removeClass('show')
            $('.radio_group_sql').removeClass('show')
        }
        if ($(this).val() == 'R') {
            $('.radio_group_position').addClass('show')
        } else {
            $('.radio_group_position').removeClass('show')
        }

    })

    var property = $('#new_property').clone(true);
    $('#new_property').remove().removeAttr('id');

    $(document).on('click', '.add_property', function() {
        var parent = $(this).parents('tbody:first');
        var clone = parent.children(':last').clone();
        var index = parseInt(clone.find('input:first').attr('name').match(/\[([0-9]+)\]/)[1]) + 1;

        // Очистить значения клонирования и обновить индекс
        clone.find('input, select').val('').each(function() {
            $(this).attr('name', $(this).attr('name').replace(/\[[0-9]+\]/, '[' + index + ']'));
        }).end().appendTo(parent);
    });

    // Удаление варианта
    $(document).on('click', '.del_variant', function() {
        if($("#properties tr").length > 1) {
            $(this).closest("tr").fadeOut(200, function() {
                $(this).remove();
            });
        } else {
            $('#variants_block td.variant_name').hide();
            $('#variants_block th.variant_name').hide();
            $('#variants_block').addClass('single_variant');
        }
        return false;
    });

</script>