<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST'); 

if (@$_REQUEST['debug']==1) {
	ini_set('display_errors', 'On');
	error_reporting('E_ALL');
}

date_default_timezone_set('europe/amsterdam');
define('APP_INCLUDE', 1);
define("VIDM_IPADDRESS", 1);  	// IP Address only
define("VIDM_IPPLUSAGENT", 2);  // IP address + user agent
define("VIDM_COOKIE", 3);
define("VIDM_CUSTOM_COOKIE", 4);
if (isset($_REQUEST['dbid']) && !empty($POST['dbid'])) {
	include("../files/global.{$POST['dbid']}.php");
} else {
	include("../files/global.php");
}
include_once("table_definitions.php");
require_once("../vendor/adodb/adodb-php/adodb.inc.php");
require_once("../Core.php");

if (function_exists("mysqli_connect")) {
	$db = ADONewConnection("mysqli");
} else {
	$db = ADONewConnection("mysql");
	//echo "connecting mysql";
}
$db->Connect($mysqlserver,$mysqluname,$mysqlpw, $DatabaseName);

function CheckIfTableExists($table){
	global $db;

    $R = $db->getRow("SELECT COUNT(*) FROM information_schema.TABLES  WHERE TABLE_SCHEMA ='" . $db->database . "' AND TABLE_NAME ='" . $table . "'");
    if(0 !== $R[0] ){
        return true;
    } else {
        return false;
    }
}

function getGlobalSetting($settingname, $defaultvalue = "") {
    return getProfileData( $settingname,"", $defaultvalue);
}

function getProfileData($settingname,$profile = 'Profiles',  $defaultvalue = "" ) {
	global $db;

	$query = "Select Value from ".TBL_GLOBAL_SETTINGS ." where Name = " . $db->Quote($settingname) . " and Profile = ".$db->Quote($profile);
	if (!($result = @$db->GetRow($query))) {
		return $defaultvalue;
	}
	if (count($result) > 0) {
		return $result[0];
	} else {
		return $defaultvalue;
	}
}

if(empty($_POST['conf'])){
	die('{ "Status" : "Error" , "Message" : "Missing params." }');	
}

$conf = $_POST['conf'];
$action = @$_POST['action'];
$surveyID = @$_POST['survey_id'];

if(empty($action)){
	die('{ "Status" : "Error" , "Message" : "Missing params." }');	
}

if(empty($surveyID) || !is_numeric($surveyID) ){
	die('{ "Status" : "Error" , "Message" : "Invalid Surveys ID." }');
}

include_once("siteprofile.php");
$profile = new SiteProfile($conf);

$surveyT = $profile->tablename."_surveys";
$surveyQ = $profile->tablename."_surveyquestions";
$surveyR = $profile->tablename."_surveyresults";

if(!checkIfTableExists($surveyT)){
	die('{ "Status" : "Error" , "Message" : "Surveys are not installed for $conf." }');
}

function GetQuestions(){
	global $surveyQ, $surveyID, $db;

	$q = "SELECT * FROM {$surveyQ} where surveyid = ? ORDER BY question_order";

	$r = $db->Execute($q, array( intval($surveyID)));

	$questions = [];
	while($row = $r->fetchRow()){
		if(!empty($row["question_rule"])){
			$d = json_decode($row["question_rule"], true);
			$row["answers"] = $d['answers'];
			$row["options"] = $d['options'];
			$row["a_type"] = $d['a_type'];
		}

		$questions[] = array(
			"id" => intval($row['id']),
			"question" => $row['question'],
			"type" => $row['question_type'],
			"answers" => @$row["answers"],
			"options" => @$row["options"],
			"rules" => json_decode($row['answer_rule'],true)
		);
	}
	return $questions;
}

$ipnumber = $_SERVER["REMOTE_ADDR"];
$useragent = $_SERVER['HTTP_USER_AGENT'];

if ($profile->visitoridentmethod == VIDM_IPADDRESS) {
	$visitorid = md5($ipnumber);

} else if ($profile->visitoridentmethod == VIDM_COOKIE && isset($_COOKIE['NewLogaholic_VID'])) {
	$visitorid = md5($_COOKIE['NewLogaholic_VID']);

} else if ($profile->visitoridentmethod == VIDM_CUSTOM_COOKIE && isset($_COOKIE[$profile->vidm_custom_cookie])) {
	$visitorid = $_COOKIE[$profile->vidm_custom_cookie];

} else { #if ($profile->visitoridentmethod == VIDM_IPPLUSAGENT) {
	$visitorid = md5($ipnumber . ':' . $useragent);	
}

# If we are posting an answer check if it is not empty but it can be 0...
if($action == "POST"){
	$answers = [];
	foreach ($_POST as $k => $v) {
		$a = strpos($k, "answer");

		if($a !== false){
			$qid = substr($k, 7);
			$answers[intval($qid)] = $v;
		}
	}

	$questions = GetQuestions();

	$inserts = [];

	foreach ($questions as $q) {
		if(isset($answers[$q['id']])){
			$a = $answers[$q['id']];
			$answer;
			
			if($q['type'] == "open" || $q['type'] == "input"){
				# It's all good.. keep it as it is.
				$answer = $a;

			} else if($q['type'] == "single"){
				$answer = $q['answers'][$a];

			} else if($q['type'] == "multiple"){
				$keys = explode("-", $a);
				$answer = [];
				foreach($q['answers'] as $key => $val) {
					if(intval($keys[$key]) > 0){
						$answer[] = $val;
					}					
				}

			}
			$inserts[$q['id']] = $answer;		
		}
	}

	

	$query = "insert into {$profile->tablename}_surveyresults (`surveyid`, `visitorid`, `timestamp`, `questionid`, `answer`) VALUES (?, ?, ?, ?, ? )";
	foreach ($inserts as $id => $answer) {
		if(is_array($answer)){
			foreach ($answer as $k => $v){
				$db->Execute($query, array(
					$surveyID,
					$visitorid,
					time(),
					$id,
					$v
				));
			}
		} else {
			$db->Execute($query, array(
				$surveyID,
				$visitorid,
				time(),
				$id,
				$answer
			));
		}
	}

	die('{ "Status" : "Success" , "Message" : "Received Answers" }');

} else if($action == "GET"){

	$r = $db->Execute("SELECT surveyoptions FROM {$surveyT} WHERE id = {$surveyID}");
	$row = $r->fetchRow();
	$options = json_decode($row['surveyoptions'],true);

	if(empty($options["closingmsg"])){
		$options["closingmsg"] = "Thank You for completing our survey.";
	}

	if(!empty($options["only_once"]) ){
		$q = $db->Execute("SELECT count(*) as answers FROM {$surveyR} WHERE surveyid = {$surveyID} and visitorid='$visitorid'");		
		if ($row = $q->fetchRow()) {
			if ($row['answers'] > 0) {
				die('{ "Status" : "Success" , "Message" : "Already done" }');
			}
		}		
	}	

	$questions = GetQuestions();	
	die('{ "Status" : "Success" , "Message" : "'. $options["closingmsg"] .'", "Data" : '. json_encode($questions) .' }');
}


die('{ "Status" : "Error" , "Message" : "Missing params." }');	
?>