<?php

function insertOption($surveyId, $question, $option, $text, $pdo) {

    // Prepare the SQL insert statement
    $stmt = $pdo->prepare("INSERT INTO Filters (surveyId, FilterQuestion, FilterOption, Text) VALUES (:survey, :question, :option, :text)");

    $stmt->execute([
        ':survey' => $surveyId,
        ':question' => $question,
        ':option' => $option,
        ':text' => $text
    ]);

}

// Load config
$config = require 'config.php';
$apiToken = $config['api_token'];
$dataCenter = $config['data_centre'];

// Get the survey ID from POST
$surveyId = $_POST['surveyId'] ?? null;
if (!$surveyId) {
    //$surveyId="SV_cAstEvm4ZrPaqGi";	
    //$surveyId="SV_cwKjMqAqGxImjMG";	
    die("No survey ID provided.");
}

// Build URL
$baseUrl = "https://$dataCenter.qualtrics.com/API/v3";
$questionsUrl = "$baseUrl/survey-definitions/$surveyId/questions";

// Set headers
$headers = [
    "X-API-TOKEN: $apiToken",
    "Content-Type: application/json"
];

// Make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $questionsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    die("Request error: " . curl_error($ch));
}

curl_close($ch);

// Output the raw JSON
//header('Content-Type: application/json');
//echo $response;
//var_dump($response);

$data = json_decode($response, true);

// Database connection (PDO)
$pdo = new PDO("mysql:host=localhost;dbname={$config['db_name']};charset=utf8mb4", $config['db_user'], $config['db_pass']);

//Check if the survey data has previously been inserted:
$checkSql = "SELECT 1 FROM Filters WHERE surveyId = :surveyId LIMIT 1";

$stmt = $pdo->prepare($checkSql);
$stmt->execute([
    ':surveyId' => $surveyId
]);

if ($stmt->fetch()) {
    echo "Custom user qualifiers already exported for this particular survey ({$surveyId}) .<br>".PHP_EOL;
    echo "This process only ever needs to be carried out once for each survey.<br>".PHP_EOL;
    echo "Skipping data export.<br>".PHP_EOL;
    echo "<br><br>";
    echo "You now need to <a href='./getSurveys.php'>go and export the answer data</a> before you can <a href='./reportTemplate.html'>get the survey reports</a>";


    return;
}


if (isset($data['result']['elements']) && is_array($data['result']['elements'])) {
    foreach ($data['result']['elements'] as $element) {
        if (isset($element['QuestionID'])) {
            
            /* if (isset($element['QuestionID']) && $element['QuestionID'] === "QID71") {
                //echo json_encode($element, JSON_PRETTY_PRINT) . PHP_EOL;
            }*/ 

            if (isset($element['QuestionID']) && $element['QuestionID'] === "QID68") {
                echo "Survey: {$surveyId}, QuestionID: {$element['QuestionID']} : Description: {$element['QuestionDescription']} : 0 ". PHP_EOL;
                insertOption($surveyId, 1, 0, $element['QuestionDescription'], $pdo);
                foreach ($element['Choices'] as $index => $choice) {
                    insertOption($surveyId, 1, $index, $choice['Display'], $pdo);
                    echo "ID: $index, Display: " . $choice['Display'] . "<br>";
                }
            }
            if (isset($element['QuestionID']) && $element['QuestionID'] === "QID69") {
                echo "Survey: {$surveyId}, QuestionID: {$element['QuestionID']} : ";
                echo "Description: {$element['QuestionDescription']} : 0 ". PHP_EOL;
                insertOption($surveyId, 2, 0, $element['QuestionDescription'], $pdo);
                foreach ($element['Choices'] as $index => $choice) {
                    insertOption($surveyId, 2, $index, $choice['Display'], $pdo);
                    echo "ID: $index, Display: " . $choice['Display'] . "<br>";
                }
            }
            if (isset($element['QuestionID']) && $element['QuestionID'] === "QID71") {
                echo "Survey: {$surveyId}, QuestionID: {$element['QuestionID']} : ";
                echo "Description: {$element['QuestionDescription']} : 0 ". PHP_EOL;
                insertOption($surveyId, 3, 0, $element['QuestionDescription'], $pdo);
                foreach ($element['Choices'] as $index => $choice) {
                    insertOption($surveyId, 3, $index, $choice['Display'], $pdo);
                    echo "ID: $index, Display: " . $choice['Display'] . "<br>";
                }
            }
        }
    }
} else {
    echo "No elements found.";
}

?>
