<?php

// Settings
$config = require 'config.php';


$host = $config['db_host'];
$db   = $config['db_name'];
$user = $config['db_user'];
$pass = $config['db_pass'];
echo $user.":".$pass.":".$host.":".$db;
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // throw exceptions on error
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,       // fetch results as associative arrays
    PDO::ATTR_EMULATE_PREPARES   => false,                  // use native prepared statements
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}


// ...and now the functions

function getOrCreateSurvey($surveyId, $description = '') {
    global $pdo;

    // Step 1: Check if survey exists
    $check = $pdo->prepare("SELECT id FROM Surveys WHERE surveyId = :surveyId");
    $check->execute(['surveyId' => $surveyId]);
    $existing = $check->fetch();

    if ($existing) {
        return $existing['id'];
    }

    // Step 2: Insert if not found
    $insert = $pdo->prepare("
        INSERT INTO Surveys (surveyId, description)
        VALUES (:surveyId, :description)
    ");
    $insert->execute([
        'surveyId' => $surveyId,
        'description' => $description
    ]);


    // Step 3: Get the id
    $check = $pdo->prepare("SELECT id FROM Surveys WHERE surveyId = :surveyId");
    $check->execute(['surveyId' => $surveyId]);
    $existing = $check->fetch();
    return $existing['id'];
}

function upsertResponse($response) {
    global $pdo;

    $sql = "
        INSERT INTO Responses (
            responseId, surveyId, startDate, endDate, status, ipAddress,
            progress, duration, finished, recordedDate, locationLatitude,
            locationLongitude, distributionChannel, userLanguage
        ) VALUES (
            :responseId, :surveyId, :startDate, :endDate, :status, :ipAddress,
            :progress, :duration, :finished, :recordedDate, :locationLatitude,
            :locationLongitude, :distributionChannel, :userLanguage
        )
        ON DUPLICATE KEY UPDATE
            surveyId = VALUES(surveyId),
            startDate = VALUES(startDate),
            endDate = VALUES(endDate),
            status = VALUES(status),
            ipAddress = VALUES(ipAddress),
            progress = VALUES(progress),
            duration = VALUES(duration),
            finished = VALUES(finished),
            recordedDate = VALUES(recordedDate),
            locationLatitude = VALUES(locationLatitude),
            locationLongitude = VALUES(locationLongitude),
            distributionChannel = VALUES(distributionChannel),
            userLanguage = VALUES(userLanguage)
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($response);

    $selectStmt = $pdo->prepare("SELECT id FROM Responses WHERE responseId = :responseId");
    $selectStmt->execute(['responseId' => $response['responseId']]);
    $existing = $selectStmt->fetch(PDO::FETCH_ASSOC);
    if ($existing) {
        return $existing['id'];
    } else {
            return null; // not found, something unexpected happened
    }
}


function insertAnswers($pdo, $surveyId, $responseId, $answers) {

$stmt = $pdo->prepare("
    INSERT INTO Answers (surveyId, responseId, QID, text, value)
    VALUES (:surveyId, :responseId, :QID, :text, :value)
    ON DUPLICATE KEY UPDATE
        text = VALUES(text),
        value = VALUES(value)
");

    foreach ($answers as $key => $val) {
        if (strpos($key, 'QID') === 0) {
            $qid = $key;
            $text = null;
            $value = null;

            // Handle numeric between -3 and +3
            if (is_numeric($val) && $val >= -3 && $val <= 100) {
                $value = (int) $val;
            } else {
                $text = substr($val, 0, 255);  // enforce VARCHAR(255) limit
            }

            $stmt->execute([
                'surveyId'   => $surveyId,
                'responseId' => $responseId,
                'QID'        => $qid,
                'text'       => $text,
                'value'      => $value
            ]);

            if ($qid == "QID68"){
                if ($value === 'null' || is_null($value)) {
                    $value = 0;
                }
                updateResponseQ1($pdo, $value, $responseId);
            }
           if ($qid == "QID69"){
                if ($value === 'null' || is_null($value)) {
                    $value = 0;
                }
                updateResponseQ2($pdo, $value, $responseId);
            }
            if ($qid == "QID71"){
                if ($value === 'null' || is_null($value)) {
                    $value = 0;
                }
                updateResponseQ3($pdo, $value, $responseId);
            }




        }
    }
}


function updateResponseQ1(PDO $pdo, int $q1Value, string $responseId): bool {
    $sql = "UPDATE Responses SET Q1 = :q1 WHERE id = :responseId";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':q1', $q1Value, PDO::PARAM_INT);
    $stmt->bindParam(':responseId', $responseId, PDO::PARAM_STR);
    
    return $stmt->execute();
}

function updateResponseQ2(PDO $pdo, int $q2Value, string $responseId): bool {
    $sql = "UPDATE Responses SET Q2 = :q2 WHERE id = :responseId";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':q2', $q2Value, PDO::PARAM_INT);
    $stmt->bindParam(':responseId', $responseId, PDO::PARAM_STR);
    
    return $stmt->execute();
}

function updateResponseQ3(PDO $pdo, int $q3Value, string $responseId): bool {
    $sql = "UPDATE Responses SET Q3 = :q3 WHERE id = :responseId";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':q3', $q3Value, PDO::PARAM_INT);
    $stmt->bindParam(':responseId', $responseId, PDO::PARAM_STR);
    
    return $stmt->execute();
}

?>
