<?php
// Settings
$config = require 'config.php';
require_once 'db.php';	// include the connection
$apiToken = $config['api_token'];
$dataCentre = $config['data_centre'];
$surveyId = $_POST['survey_id'] ?? null;

if (!$surveyId) {
	$surveyId="SV_cwKjMqAqGxImjMG";   // *****FIXME***** JUST FOR DEVELOPMENT 
	//die("No survey ID provided.");
}

$baseUrl = "https://$dataCentre.qualtrics.com/API/v3";
$headers = [
    "X-API-TOKEN: $apiToken",
    "Content-Type: application/json"
];

// Step 1: Start the export (with compress = false)
$exportUrl = "$baseUrl/surveys/$surveyId/export-responses/";
$postFields = json_encode([
    "format" => "json",
    "compress" => false
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $exportUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL Error: " . curl_error($ch);
    curl_close($ch);
    exit;
}

curl_close($ch);

$result = json_decode($response, true);
echo "<pre>".$surveyId."     ".$exportUrl."</pre>";
if (!isset($result['result']['progressId'])) {
    
    echo "<pre>Export API Response:\n";
    print_r($response);
    echo "</pre>";
    die("Failed to start export.\n$response");
}
$progressId = $result['result']['progressId'];

echo "Polling for completion";



// Step 2: Poll for completion
$progressUrl = "$exportUrl/$progressId";
do {
    sleep(2); // avoid hammering the API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $progressUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);
    $status = $result['result']['status'] ?? 'failed';
} while ($status !== 'complete' && $status !== 'failed');

if ($status !== 'complete') {
    die("Export failed or timed out.\n$response");
}

$fileId = $result['result']['fileId'];

// Step 4: Download the file (uncompressed JSON)
$downloadUrl = "$exportUrl/$fileId/file";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $downloadUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    die("Error downloading the file: " . curl_error($ch));
}

curl_close($ch);

// Decode the response
$data = json_decode($response, true);

//For testing only
echo $response;


//Save surveyId
//insertSurveyIfNotExists($identifier, $description);	// The identifier is actually the surveyId, and the description isn't included at this point.
$surveyIndex = getOrCreateSurvey($surveyId, "");	

echo "-------".$surveyIndex."-----------";

// $data = $result['result'][''] ?? [];
echo "Total responses: " . count($data['responses']) . "\n\n<br>";

if (isset($data['responses']) && is_array($data['responses'])) {
    foreach ($data['responses'] as $response) {
	echo "Response ID: " . $response['responseId'] . "\n";
	//Insert responseId into the database
	//
	$startDate = new DateTime($response['values']['startDate']);
	$startDateFormatted = $startDate->format('Y-m-d H:i:s');
	$endDate = new DateTime($response['values']['endDate']);
	$endDateFormatted = $endDate->format('Y-m-d H:i:s');
	$recordedDate = new DateTime($response['values']['recordedDate']);
	$recordedDateFormatted = $recordedDate->format('Y-m-d H:i:s');

	$responseData = [
	    'responseId' => $response['responseId'],
	    'surveyId' => $surveyIndex,
	    'startDate' => $startDateFormatted,
	    'endDate' => $endDateFormatted,
	    'status' => $response['values']['status'],
	    'ipAddress' => $response['values']['ipAddress'] ?? '0.0.0.0',
	    'progress' => $response['values']['progress'],
	    'duration' => $response['values']['duration'],
	    'finished' => $response['values']['finished'],
	    'recordedDate' => $recordedDateFormatted,
	    'locationLatitude' => $response['values']['locationLatitude'] ?? '0.0',
	    'locationLongitude' => $response['values']['locationLongitude'] ?? '0.0',
	    'distributionChannel' => $response['values']['distributionChannel'],
	    'userLanguage' => $response['values']['userLanguage'] ?? 'en'
	];


	$responseIndex = upsertResponse($responseData);	
	// Now read in the answers. These all start with QID????? etc
	$answers = $response['values'];

	insertAnswers($pdo, $surveyIndex, $responseIndex, $answers);

	// Prepare and execute the INSERT statement
	//
	//
    }
} else {
    echo "No responses found.";
}



?>

