<?php

class CustomerGroupPMConf {
	private $_db;
	private $_pm;
	private $_sa;

	function __construct($pm, $sa) {
		$this->_db = Registry::get('base')->db;
		$this->_pm = $pm;
		$this->_sa = $sa;
	}

	public function get_all() {
		$sql = "SELECT cgpmc.group_id, cgpmc.payment_method_id, cgpmc.shipping_area_id, cgpmc.active, cg.name
				FROM customer_group_payment_method_configuration cgpmc
				JOIN customer_groups cg
				WHERE cg.id = cgpmc.group_id
				AND cgpmc.payment_method_id=".$this->_db->real_escape_string($this->_pm).
				" AND cgpmc.shipping_area_id=".$this->_db->real_escape_string($this->_sa);

		$result = $this->_db->query($sql);

		if ($result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				$return[] = $obj;
			}

			return $return;
		}

		return false;
	}

	private function has_conf($group) {
		$sql = "SELECT *
					FROM customer_group_payment_method_configuration
					WHERE group_id=".$this->_db->real_escape_string($group).
					" AND shipping_area_id=".$this->_db->real_escape_string($this->_sa).
					" AND payment_method_id=".$this->_db->real_escape_string($this->_pm);

		$result = $this->_db->query($sql);

		if ($result->num_rows > 0) {
			return true;
		}

		return false;
	}

	public function update($data) {
		$sql =  "UPDATE customer_group_payment_method_configuration
					SET active=".$this->_db->real_escape_string($data['active']).
					" WHERE group_id=".$this->_db->real_escape_string($data['group']).
					" AND shipping_area_id=".$this->_db->real_escape_string($this->_sa).
					" AND payment_method_id=".$this->_db->real_escape_string($this->_pm);

		$this->_db->query($sql);
	}

	public function create($data) {
		$sql = "INSERT INTO
				customer_group_payment_method_configuration (group_id, payment_method_id, shipping_area_id, active)
				VALUES (".$this->_db->real_escape_string($data['group']).
				" , ".$this->_db->real_escape_string($this->_pm).
				" , ".$this->_db->real_escape_string($this->_sa).
				" , ".$this->_db->real_escape_string($data['active']).
				" )";

		$this->_db->query($sql);
	}

	public function delete() {

	}

	public function save($data) {
		if ($this->has_conf($data['group'])) {
			$this->update($data);
		} else {
			$this->create($data);
		}
	}

	public function save_array($data) {
		foreach ($data as $point) {
			$this->save($point);
		}
	}
}
