<?php

class Sistema_Model_CorretoresPeriodoCadastroAnual extends Agro_Db_Table_Abstract
{
    protected $_schema = 'sistema';
    protected $_primary = 'id';
    protected $_name = 'corretores_periodo_cadastro_anual';

    public function getByCorretor(int $idCorretor, string $data = '', bool $fetchAllReturn = true)
    {
        $select = $this->select();
        $select->setIntegrityCheck(false);
        $select->from(["{$this->_schema}.{$this->_name}"], '*');
        $select->where('id_corretor = ?', $idCorretor);

        if (!empty($data)) {
            $select->where('dt_inicio <= ?', $data);
            $select->where('dt_fim >= ?', $data);
        }

        $select->order('dt_fim desc');

        return $fetchAllReturn ? $this->fetchAll($select) : $this->fetchRow($select);
    }

    public function save(array $data)
    {
        if (empty($data['id']) && !empty($data['id_corretor'])) {
            $row = $this->getByCorretor($data['id_corretor'], date('Y-m-d'), false);
        }

        if (empty($row)) {
            $row = $this->getRow($data['id']);
        }

        $row->id_corretor = $data['id_corretor'] ?? $row->id_corretor;
        $row->dt_inicio = $data['dt_inicio'] ?? $row->dt_inicio;
        $row->dt_fim = $data['dt_fim'] ?? $row->dt_fim;

        if (array_key_exists('fl_cadastro_inalterado', $data)) {
            $row->fl_cadastro_inalterado = $data['fl_cadastro_inalterado'] ? 'true' : 'false';
        }

        if (array_key_exists('fl_atualizacao_iniciada', $data)) {
            $row->fl_atualizacao_iniciada = $data['fl_atualizacao_iniciada'] ? 'true' : 'false';
        }

        $row->save();
    }
}
