<?php
/** 
 * @package     VikAppointments
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2021 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

VAPLoader::import('libraries.mvc.model');

/**
 * VikAppointments option variation model.
 *
 * @since 1.7
 */
class VikAppointmentsModelOptionvar extends JModelVAP
{
	/**
	 * Basic save implementation.
	 *
	 * @param 	mixed  $data  Either an array or an object of data to save.
	 *
	 * @return 	mixed  The ID of the record on success, false otherwise.
	 */
	public function save($data)
	{
		$data = (array) $data;

		/**
		 * In case we are saving the number of units remaining in stock, 
		 * check whether the new value is higher than the previous one.
		 * If this is the case, unset the flag used to check whether a 
		 * notification was already sent to the administrator.
		 * 
		 * @since 1.7.7
		 */
		if (!empty($data['id']) && !empty($data['units']))
		{
			$table = $this->getTable();
			$table->load($data['id']);

			if ($table->units < $data['units'])
			{
				// the product can be notified again
				$data['stock_notified'] = 0;
			}
		}

		return parent::save($data);
	}

	/**
	 * Extend delete implementation to delete any related records
	 * stored within a separated table.
	 *
	 * @param   mixed    $ids  Either the record ID or a list of records.
	 *
	 * @return 	boolean  True on success, false otherwise.
	 */
	public function delete($ids)
	{
		// only int values are accepted
		$ids = array_map('intval', (array) $ids);

		// invoke parent first
		if (!parent::delete($ids))
		{
			// nothing to delete
			return false;
		}

		$dbo = JFactory::getDbo();

		// load any assigned translation
		$q = $dbo->getQuery(true)
			->select($dbo->qn('id'))
			->from($dbo->qn('#__vikappointments_lang_option_value'))
			->where($dbo->qn('id_variation') . ' IN (' . implode(',', $ids) . ')' );

		$dbo->setQuery($q);

		if ($lang_ids = $dbo->loadColumn())
		{
			// get translation model
			$model = JModelVAP::getInstance('langoptionvar');
			// delete assigned translations
			$model->delete($lang_ids);
		}

		return true;
	}
}
