<?php

class Sistema_Model_TreinamentoVistorias extends Agro_Db_Table_Abstract {
	protected $_schema = 'sistema';
	protected $_name = 'treinamento_vistorias';
	protected $_primary = 'id';

	public function save(array $data)
    {
        $Row = $this->getRow($data['id']);
        $Row->id_funcionario = $data['id_funcionario'];
        $Row->id_treinamento = $data['id_treinamento'];
        $Row->fl_ministrante = ($data['fl_ministrante']) ? 't' : 'f';

        $id = $Row->save(); 
        
        if (!$id) {
            throw new Exception("Erro ao vincular o funcionário ao treinamento.");
        }

        return $id;
    }

    public function migrarTreinamentos(int $idFuncionario)
    {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('tv' => 'sistema.treinamento_vistorias'), ['id', 'id_funcionario', 'id_treinamento', 'fl_ministrante']);
        $select->join(["f" => "sistema.funcionarios"], "f.id = tv.id_funcionario", null);
        $select->where("f.cpf_cnpj in (SELECT cpf_cnpj FROM sistema.funcionarios WHERE id = {$idFuncionario})");
        $rs = $this->getAdapter()->fetchAll($select);

        foreach ($rs as $treinamentoVistoria) {
            $treinamentoVistoria['id_funcionario'] = $idFuncionario;
            $this->save($treinamentoVistoria);
        }
    }
}
