<?php

class Sistema_Model_AgendamentosFuncionarios extends Agro_Db_Table_Abstract {
	protected $_schema = 'sistema';
	protected $_name = 'agendamentos_funcionarios';
	protected $_primary = array('id_agendamento', 'id_funcionario');
	protected $_sequence = false;
	protected $_rowClass = 'Sistema_Model_Row_AgendamentosFuncionarios';
	
	public function save(array $data) {

		try{

			$Row = $this->createRow();

			$Row->id_agendamento = $data['id_agendamento'];
			$Row->id_funcionario = $data['id_funcionario'];
			$Row->fl_principal = $data['fl_principal'] ? 1 : 0;

			return $Row->save();			

		}catch (Exception $e){
			die($e);
		}	

	}
	
	public function delete($idAgendamento) {

		$this->_db->query("delete from {$this->_schema}.{$this->_name} where id_agendamento = $idAgendamento");
	}


	/**
	 * Retorna o vistoriador vinculado ao agendamento
	 * 
	 * @param int $idAgendamento
	 * @param bool $isPrincipal
	 * @return array
	 */
	public function getVistoriador(int $idAgendamento, bool $isPrincipal = false): array
	{
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('af'=>'sistema.agendamentos_funcionarios'), ['id_funcionario']);
		$select->join(array('f' =>'sistema.funcionarios'),'f.id = af.id_funcionario', ['ds_nome_funcionario', 'id_empresa']);
		$select->where('af.id_agendamento = ?', $idAgendamento);
		$select->where('af.fl_principal = ?', $isPrincipal ? '1' : '0');
		$rs = $this->fetchRow($select);

		return !empty($rs) ? $rs->toArray() : [];
	}

	public function getVistoriadorByIdVistoria(int $idVistoria, bool $isPrincipal = false): ?Sistema_Model_Row_AgendamentosFuncionarios 
	{
		return $this->fetchRow(
			$this->select()
				->setIntegrityCheck(false)
				->from(array('af'=>'sistema.agendamentos_funcionarios'), ['id_funcionario'])
				->join(array('va' =>'sistema.vistorias_agendamentos'),'va.id_agendamento = af.id_agendamento', null)
				->join(array('f' =>'sistema.funcionarios'),'f.id = af.id_funcionario', ['ds_nome_funcionario', 'id_empresa'])
				->join(array('e' => 'sistema.empresas'), 'e.id = f.id_empresa', ['ds_nome_fantasia'])
				->where('va.id_vistoria = ?', $idVistoria)
				->where('af.fl_principal = ?', $isPrincipal ? '1' : '0')
		);
	}
}
