<?php
require_once './jsonrpcphp/src/org/jsonrpcphp/JsonRPCClient.php';

include 'config.php';


$lsJSONRPCClient = new org\jsonrpcphp\JsonRPCClient($rpcUrl);
$sessionKey= $lsJSONRPCClient->get_session_key($rpcSessionUser,$rpcSessionPassword );
//~ If an error happen
if(is_array($sessionKey))
{
    print_r($sessionKey);
    die();
}

$excludedSids = array(1, 2, 4);


$surveys = $lsJSONRPCClient->list_surveys(
	    $sessionKey
    );
if(is_array($surveys)) {
	// Print all Array Elements
	print_r($surveys);
	}
if(is_array($surveys)) {
      print "\nStart iteration over surverys\n";
      foreach($surveys as $survey) {
            if (in_array($survey['sid'], $excludedSids)) {
                    echo $survey['sid'] . " is excluded, go next\n";
                    continue; // Skip the current iteration if excluded sid is encountered
                }
//                $survey['sid']=644242;
            	echo "begin to fetch " . $survey['sid'] . "\n";
            	$result = $lsJSONRPCClient->export_statistics(
	    			$sessionKey,$survey['sid'],"xls"
    			);
    		echo "\nResult feteched\n";
    		echo "Result lenght:" . strlen($result) . "\n";
    		$filecontent = base64_decode($result);
    		echo $filecontent;
    		$exportdir='/ram/'.$survey['sid'];
    		if (!file_exists($exportdir)) {
				mkdir($exportdir, 0770, true);
				}
			$filepath=$exportdir.'/'.$survey['sid'].'_Statistik.xls';
			$success = file_put_contents($filepath, $filecontent);
			print $success ? $filepath : "Unable to save the file.\n";
                	//echo "\t Var Dump : ". var_dump($result) ."\r";
                	//echo "\t Survey list : ". print_r($result);
				//echo json_encode($result);
            	
            }
		//print_r($surveys);
        //echo $surveys[1]['sid'];
                //echo "\t Error happen : ". print_r($surveys);
	    } else {
		echo gettype($surveys)."\n";
                //echo "\t Var Dump : ". var_dump($surveys) ."\r";
                //echo "\t Survey list : ". print_r($surveys);
		//echo json_encode($surveys);
            }


/*    $result = $lsJSONRPCClient->export_statistics(
	    $sessionKey,221001,'xls'
    );
            if(is_array($result)) {
		print_r($result);
                //echo "\t Error happen : ". print_r($result);
	    } else {
		echo gettype($result)."\n";
		$filecontent = base64_decode($result);
		$filepath='./'.uniqid().'.xls';
		$success = file_put_contents($filepath, $filecontent);
		print $success ? $filepath : 'Unable to save the file.';
                //echo "\t Var Dump : ". var_dump($result) ."\r";
                //echo "\t Survey list : ". print_r($result);
		//echo json_encode($result);
            }
            */
//~ release the session key
$lsJSONRPCClient->release_session_key( $sessionKey );
