<?php
header('Content-Type: application/json');

if (php_sapi_name() === 'cli') {
    echo "Running from command line.\n";
    $surveyId="SV_cwKjMqAqGxImjMG";

} else {
    //echo "Running from browser.\n";
    // Basic input validation and sanitization
    if (!isset($_POST['surveyId']) || empty($_POST['surveyId'])) {
        echo json_encode(['error' => 'Missing surveyId parameter']);
        exit;
    }
  
    $input = $_POST['surveyId'] ?? '';


    if (preg_match('/^SV_[a-zA-Z0-9]+$/', $input)) {
        // Input is valid
        $surveyId = $input;
    } else {
        // Invalid format
        die("Invalid survey ID format.");
    }


}


// Database connection (adjust credentials accordingly)
//
$config = require 'config.php';
$host = $config['db_host'];
$db   = $config['db_name'];
$user = $config['db_user'];
$pass = $config['db_pass'];
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);

    $sql = "
        SELECT FilterQuestion, FilterOption, Text
        FROM Filters
        WHERE surveyId = :surveyid
        ORDER BY FilterQuestion, FilterOption
    ";

    //echo $sql;

    $stmt = $pdo->prepare($sql);
    $stmt->execute(['surveyid' => $surveyId]);
    $results = $stmt->fetchAll();

    //print_r($results);

    $grouped = [];
    foreach ($results as $result) {
        $question = $result['FilterQuestion'];
        $option = $result['FilterOption'];
        $text = $result['Text'];
        $grouped[$question][$option] = $text;
    }

    echo json_encode($grouped);

} catch (PDOException $e) {
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    exit;
}











