<?php

defined('HOSTCMS') || exit('HostCMS: access denied.');

/**
 * Admin_Form_Field_Settings_Controller
 *
 * @package HostCMS
 * @subpackage Admin_Form
 * @version 7.x
 * @copyright © 2005-2024, https://www.hostcms.ru
 */
class Admin_Form_Field_Setting_Controller extends Admin_Form_Action_Controller
{
	/**
	 * Executes the business logic.
	 * @param mixed $operation Operation name
	 */
	public function execute($operation = NULL)
	{
		$oUser = Core_Auth::getCurrentUser();

		if ($this->_object->id && !is_null($oUser))
		{
			$aExistFormFieldSettings = array();

			$oAdmin_Form_Field_Settings = $this->_object->Admin_Form_Field_Settings;
			$oAdmin_Form_Field_Settings->queryBuilder()
				->where('user_id', '=', $oUser->id);

			$aAdmin_Form_Field_Settings = $oAdmin_Form_Field_Settings->findAll(FALSE);
			foreach ($aAdmin_Form_Field_Settings as $oAdmin_Form_Field_Setting)
			{
				$aExistFormFieldSettings[$oAdmin_Form_Field_Setting->admin_form_field_id] = $oAdmin_Form_Field_Setting;
			}

			$oAdmin_Form_Fields = $this->_object->Admin_Form_Fields->findAll(FALSE);
			foreach ($oAdmin_Form_Fields as $oAdmin_Form_Field)
			{
				if (isset($_POST['admin_form_field' . $oAdmin_Form_Field->id]))
				{
					if (isset($aExistFormFieldSettings[$oAdmin_Form_Field->id]))
					{
						unset($aExistFormFieldSettings[$oAdmin_Form_Field->id]);
					}
					else
					{
						// Создаем новый
						$oAdmin_Form_Field_Setting = Core_Entity::factory('Admin_Form_Field_Setting');
						$oAdmin_Form_Field_Setting->admin_form_id = $this->_object->id;
						$oAdmin_Form_Field_Setting->admin_form_field_id = $oAdmin_Form_Field->id;
						$oAdmin_Form_Field_Setting->user_id = $oUser->id;
						$oAdmin_Form_Field_Setting->save();
					}
				}
			}

			// Удаляем оставшиеся, которые не были отмечены
			foreach ($aExistFormFieldSettings as $oAdmin_Form_Field_Setting)
			{
				$oAdmin_Form_Field_Setting->delete();
			}

			$this->addMessage("<script>$(function() {
				$('#adminFormSettingsModal" . $this->_object->id . "').modal('hide');
				mainFormLocker.unlock();
				$.loadingScreen('show');
				$('#id_content #refresh-toggler').click();
			});</script>");
		}

		return TRUE;
	}
}