<?php 

namespace HMRC\Response;

use GuzzleHttp\Psr7\Response as GuzzleResponse;
use HMRC\HTTP\Code;

function setValues($type,$arr,$c){
if(!is_array($arr)){}
else{
$con=mysqli_connect("localhost", "dasoid_test", "carvan855","dasoid_vat") or die(mysqli_error());
//echo "Count=".$c."<br>";
//echo "Type=".$type."<br>";
foreach($arr as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$fields .= "'$val'";
}

if($type=='obligations'){
if($c==5){$append=",'NULL'";$join=$fields.$append;}
else{$join=$fields; $append="";}
}
if($type=='vat_submit'){
if($c==3){$append=",'NULL'";$join=$fields.$append;}
else{$join=$fields; $append="";}
}

if($type=='vat_return'){
$join=$fields; $append="";
}
//else{$join=$fields; $append="";}

//$stmt = $GLOBALS['con']->prepare("SELECT * FROM `".$type."` WHERE `periodKey`='".$_REQUEST['name']."'")or die(mysqli_error($GLOBALS['con']));
//$stmt->execute();$iv=$stmt->get_result();$stmt->close();
//$n=mysqli_num_rows($iv);

if($c==0){}
else{echo $c."-".$join."<br>";
$stmt = $con->prepare("INSERT INTO `".$type."` VALUES(NULL,$join)")or die(mysqli_error($con));
$stmt->execute();$stmt->close();

//echo $type."<br>";
}
}
}


function printValues($arr,$type) {
$count=0;
$insert=array();
global $values;
if(!is_array($arr)){die("ERROR: Input is not an array");}
foreach($arr as $key=>$value){
if(is_array($value)){printValues($value,$type);}
else{
$values[] = $key.": ".$value;
$insert[$key] = $value;

$count++;
}
}
setValues($type,  $insert, $count);
return array('total' => $count, 'values' => $values);
}

class Response{

private $response;

public function __construct(GuzzleResponse $response){$this->response = $response;}

public function isSuccess(): bool{return $this->response->getStatusCode() == Code::SUCCESS;}

public function getBody(){return $this->response->getBody();}

public function getJson(bool $assoc = false){return json_decode((string) $this->response->getBody(), $assoc);}

public function getArray(){return $this->getJson(true);}

public function echoBodyWithJsonHeader(){
$str= (string) $this->getBody();
$str=json_decode($str, true);
$result = printValues($str);
echo $type;
echo implode("<br>", $result["values"]);
}
    
public function echoObsHeader(){
$str= (string) $this->getBody();
$str=json_decode($str, true);
$result = printValues($str,'obligations');
echo "Obligation response <br>";
echo implode("<br>", $result["values"]);
}

public function echoSubmitHeader(){
$str= (string) $this->getBody();
$str=json_decode($str, true);
$result = printValues($str,'vat_submit');
echo "Return response <br>";
echo implode("<br>", $result["values"]);
}

public function echoReturnHeader(){
$str= (string) $this->getBody();
$str=json_decode($str, true);
$result = printValues($str,'vat_return');
echo "Return response <br>";
echo implode("<br>", $result["values"]);
}
  

public function getGuzzleResponse(): GuzzleResponse{
return $this->response;
}

}
