<?php

class Atendimento_Model_ContatoTelefones extends Agro_Db_Table_Abstract {
	protected $_schema = 'atendimento';
	protected $_name = 'contatos_telefones';
	protected $_primary = 'id';
	
	public function save(array $data) {
		$Row = ($data['id'] ? $this->find($data['id'])->current() : $this->createRow());
		//$Row = $this->getRow($data['id']);
		
		$Row->id_tipo_telefone = intval($data['id_tipo_telefone']);
		$Row->id_contato = $data['id_contato'];
		$Row->ds_numero = $data['ds_numero'];
		$Row->ds_ramal = $data['ds_ramal'];
		
		return $Row->save();
	}
	
	public function getData($where) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('t' => 'atendimento.contatos_telefones'));
		$select->join(array('tt' => 'sistema.tipo_telefone'), 't.id_tipo_telefone = tt.id', 'tp_telefone');
		
		foreach ($where as $clause) {
			$field = $clause['field'];
			$operator = $clause['operator'];
			$value = $clause['value'];
			
			$select->where("$field $operator ?", $value);
		}

		$select->order('tp_telefone');

		return $select;
	}
	
	public function getTelefones($id_contato) {
		$select = $this->getData(array());
		$select->where("id_contato = $id_contato");
		$ret = $this->_db->fetchAll($select);
		return $ret;
		
	}
	
	public function getTelefonesListagem($id_contato) {
		$select = $this->getData(array());
		$select->where("id_contato = $id_contato");
		$Rs = $this->_db->fetchAll($select);
		$ret = array();
		foreach($Rs as $tel) {
			$ret[] = $tel['ds_numero'] . ($tel['ds_ramal'] != '' ? ' - ' . $tel['ds_ramal'] : '');
		}
		if(is_array($ret)) {
			$ret = implode('<br>', $ret);
		}
		return $ret;
	}
}