<?php

namespace App\DAO;

use App\DAO\DAO;
use App\DAO\DAOResponse\DAOResponse;
use App\DAO\DAOResponse\DAOResponseInterface;
use App\Utils\DateUtils;

class PagSeguroRequestDAO extends DAO {

	public function registerRequest(string $objrequest, string $url, string $referenceid, int $idlojacompra): DAOResponse {

		$daoResponse = new DAOResponse();

		// $json = json_encode( $objrequest, JSON_UNESCAPED_UNICODE );

		$sql = <<<SQL
			insert into pagseguro_request 
				(id_loja_compra,reference_id,data_criacao,hora_criacao,url_request,request) values
				(:loja_compra_id:, :idreferencia:,:data_c:,:hora_c:,:url_req:, :objreq:)
		SQL;

		$binds = [ 
			'loja_compra_id' => $idlojacompra,
			'idreferencia' => $referenceid,
			'data_c' => DateUtils::today(),
			'hora_c' => DateUtils::now_time(),
			'url_req' => $url,
				'objreq' => $objrequest
		];
		
		$conn = db_connect();
		$numrows = $conn->query( $sql, $binds )->numRows;
		$errors = $conn->error();
		
		if ($errors ['code'] != 0) {
			$daoResponse->setStatus( DAOResponseInterface::DATABASE_CONNECTION_ERROR );
			$daoResponse->setErrors( $errors );
			$daoResponse->setData( [ ] );
			log_message( "ERROR", json_encode( $errors ) );
		} else {
			$affectrows = $conn->affectedRows();
			if ($affectrows == 0) {
				$daoResponse->setStatus( DAOResponseInterface::INSUFFICIENT_DATA );
				$daoResponse->setData( [ ] );
			} else {
				$newid = $conn->insertID();
				$daoResponse->setStatus( DAOResponseInterface::SUCESS );
				$daoResponse->setData( [
						'id_request' => $newid
				] );
			}
		}

		return $daoResponse;

	}

}

