<?php

namespace Models;

/**
 * Class Ad
 * @param $f3 \Base
 * @package Models
 */
class Group extends DB_Resource {

	protected
		$fieldConf = array(
			'title' => array(
				'type' => 'VARCHAR256',
				'nullable' => false,
				'required'=>true,
			),
			'notes' => array(
					'type' => 'TEXT',
			),
			'num_display' => array(
				'type' => 'INT2',
				'default' => 1,
				'required'=>true,
			),
			'ad_break' => array(
				'type' => 'VARCHAR256',
			),
			'ad_order' => array(
					'type' => 'VARCHAR256',
			),
			'ad_order_type' => array(
					'type' => 'INT2',
					'default' => 1,
					'required'=>true,
			),
			'last_updated' => array(
				'type' => 'INT4',
			),
			'user_id' => array(
					'belongs-to-one' => '\Models\User',
			),
			'ads' => array(
				'has-many' => array('\Models\Ad','groups'),
			),
			'keywords' => array(
				'has-many' => array('\Models\Keyword','groups'),
			),
		),
		$table = 'groups';


	public function set_keywords($value = null){
		if (empty($value)) return $value;

		$keyArr = \Base::instance()->split($value);
		$key_res = new Keyword();

		// Find IDs of known Keywords
		$known_keys = $key_res->find(array('keyword IN ?', $keyArr));
		$keys = array();
		if ($known_keys){
			foreach ($known_keys as $key){
				$keys[$key->_id] = $key->keyword;
			}
			$newKeys = array_diff($keyArr, array_values($keys));
		} else
			$newKeys = $keyArr;

		foreach ($newKeys as $key){
			$key_res->reset();
			$key_res->keyword = $key;
			$out = $key_res->save();
			$keys[$out->_id] = $out->keyword;
		}
		$value = array_keys($keys);
		return $value;
	}

	public function get_keywords($value = null){
		if (empty($value)) return $value;

		$return = '';
		foreach ($value as $key){
			$return .= $key['keyword'].',';
		}

		return(trim($return, ','));
	}

	/**
	 * @param null $value
	 * @return int|null
	 */
	public function get_num_display($value = null) {
		if ($value == null) {
			return 1;
		} else {
			return ($value);
		}
	}


	/**
	 * @param null $value
	 * @return int|null
	 */
	public function get_ad_break($value = null) {
		if ($value == null) {
			return '';
		} else {
			return ($value);
		}
	}


	/**
	 * @param null $value
	 * @return int|null
	 */
	public function set_ad_break($value = null) {
		if ($value == null) {
			return '&nbsp;';
		} elseif ($value == '0'){
			$f3 = \Base::instance();
			$value = $f3->get('POST.ad_break_custom_text');
		}
		return ($value);
	}

	/**
	 * @param null $value
	 * @return int|null
	 */
	public function set_notes($value = null){
		if ($value == '<p><br></p>') return ('');
		return $value;
	}

	/**
	 * @param null $value
	 * @return int|null
	 */
	public function set_ads($value = null){
		if ($value == null) return (array());
		return $value;
	}

}