<?= $this->Form->create($menu, ['enctype' => 'multipart/form-data', 'class' => 'row g-3']) ?>
<div class="row form-area">
	<div class="col-12">

		<?php if ($level != 0): ?>
			<div class="row mb-3" id="parent_sections">
				<label class="col-md-3 col-form-label">Parent Category</label>
				<div class="col-md-7">
					<?= $this->Form->control('parent_category_id', [
						'type' => 'select',
						'class' => 'form-select',
						'options' => $parentSections,
						'label' => false,
						'empty' => '-- Select --'
					]); ?>
				</div>
			</div>
		<?php endif; ?>

		<?= $this->element('menus/form') ?>

		<div class="row">
			<div class="col-md-10 col-sm-12 d-flex justify-content-end align-items-end my-4">
				<?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary pull-right']) ?>
			</div>
		</div>
	</div>
</div>
<?= $this->Form->end() ?>

<script>
	$(document).ready(function () {
		$('#parent_category_name').val($('#parent-category-id option:selected').text());

		$('body').on('change', '#parent-category-id', function (event) {
			var category_id = $(this).val();
			var category_text = $('#parent-category-id option:selected').text();
			$('#parent_category_name').val(category_text);
			$('input[name=parent_id]').val(category_id);

			$.ajax({
				type: "POST",
				cache: false,
				processData: false,
				contentType: false,
				url: "<?= $this->Url->build(['controller' => 'Items', 'action' => 'getSections']); ?>/" + category_id,
				success: function (data) {
					data = $.parseJSON(data);
					$('#parent-category-id').html('<option value="">-- Select --</option>');
					$.each(data, function (index, item) {
						$('#parent-category-id').append(`<option value="${item.id}">${item.name}</option>`);
					});
				},
				error: function (data) {
					// Handle errors here
				}
			});
		});

		$('body').on('click', '.go-back', function (event) {
			event.preventDefault();
			$('#parent_category_name').val('');
			$.ajax({
				type: "POST",
				cache: false,
				processData: false,
				contentType: false,
				url: "<?= $this->Url->build(['controller' => 'Items', 'action' => 'getAjaxParentSections']); ?>",
				success: function (data) {
					data = $.parseJSON(data);
					$('#parent-category-id').html('<option value="">-- Select --</option>');
					$.each(data, function (index, item) {
						$('#parent-category-id').append(`<option value="${item.id}">${item.name}</option>`);
					});
				},
				error: function (data) {
					// Handle errors here
				}
			});
		});

		$('body').on('click', '#hide-section', function (event) {
			event.preventDefault();
			$('#sections-div').slideUp("slow");
		});
	});
</script>