<?php


namespace App\Models;

use App\Entities\Formulario\Formulario;
use App\Entities\Paciente\Paciente;
use App\Services\PacienteService;
use App\Services\PessoaService;
use App\Services\Service;
use App\Utils\DateUtils;
use App\Utils\ModelUtils;
use App\ViewModels\Paciente\PacienteRegistrationViewModel\PacienteRegistrationViewModel;
use CodeIgniter\Model;


class FormularioModel extends ModelEntity {
	protected $table = 'formulario';
	protected $primaryKey = 'id';
	protected $returnType = 'array';
	protected $allowedFields = [ 
			'titulo',
			'id_medico',
			'alterado_por',
			'criado_por',
			'descricao',
			'ativo'
	];
	protected $useSoftDeletes = false;
	protected $skipValidation = true;
	protected $useTimestamps = true;
	protected $createdField = 'criado_em';
	protected $updatedField = 'alterado_em';

	public function registerFormulario(Formulario $formulario): void {

		$formulario_data = $formulario->toArray( true );
		$id_formulario = $this->insert( $formulario_data );
		$formulario->setId( $id_formulario ?? 0);

	}

	public function updateFormularioSimpleByID(int $id_formulario, Formulario $formulario): bool {

		$data = $formulario->toArray( true );
		$data ['alterado_em'] = DateUtils::now();
		$binds = [ 
				'id_formulario' => $id_formulario
		];
		$sets = $this->generateUpdateSets( $data, $binds );
		$sql = "UPDATE formulario $sets WHERE formulario.id = :id_formulario:";
		log_message( 'error', $sql );
		log_message( 'error', json_encode( $data ) );
		log_message( 'error', json_encode( $binds ) );
		$query = $this->db->query( $sql, $binds );
		return $query->connID->affected_rows === 1;

	}

	public function updateStatusFormularioSimpleByID(int $id_formulario) {

		$binds = [ 
				'id_formulario' => $id_formulario
		];
		$sql = "update formulario set ativo = 0 where formulario.id = :id_formulario:";
		$query = $this->db->query( $sql, $binds );
		$result_array = $query->getResultArray();
		$error = $this->db->error();

		return $this->db->error();

	}

}
