<?php
/**
 * @version        4.3.0
 * @package        Joomla
 * @subpackage     Helpdesk Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2013 - 2021 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
namespace OSSolution\HelpdeskPro\Admin\Model;

use OSL\Model\AdminModel;

defined('_JEXEC') or die;

class Field extends AdminModel
{
	/**
	 * Store field-categories relation
	 *
	 * @param \OSSolution\HelpdeskPro\Admin\Table\Field $row
	 * @param \OSL\Input\Input                          $input
	 * @param bool                                      $isNew
	 */
	protected function afterStore($row, $input, $isNew)
	{
		$categoryIds = $input->get('category_id', array(), 'array');

		if (count($categoryIds) == 0 || $categoryIds[0] == -1)
		{
			$row->category_id = -1;
		}
		else
		{
			$row->category_id = 1;
		}

		$row->store();

		$fieldId = $row->id;
		$db      = $this->getDbo();
		$query   = $db->getQuery(true);
		$query->clear();

		if (!$isNew)
		{
			$query->delete('#__helpdeskpro_field_categories')->where('field_id = ' . $fieldId);
			$db->setQuery($query);
			$db->execute();
		}

		if ($row->category_id != -1)
		{
			$query->clear()
				->insert('#__helpdeskpro_field_categories')->columns('field_id, category_id');

			for ($i = 0, $n = count($categoryIds); $i < $n; $i++)
			{
				$categoryId = (int) $categoryIds[$i];

				if ($categoryId > 0)
				{
					$query->values("$fieldId, $categoryId");
				}
			}

			$db->setQuery($query);
			$db->execute();
		}
	}
}