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

if (php_sapi_name() === 'cli') {
    echo "Running from command line.\n";
    $qid="QID2_7";
    $survey="SV_cwKjMqAqGxImjMG";
    $q1 = 1;
    $q2 = 2;
    $q3 = 0;
} else {
    //echo "Running from browser.\n";
    // Basic input validation and sanitization
    if (!isset($_POST['qid']) || empty($_POST['qid'])) {
        echo json_encode(['error' => 'Missing QID parameter']);
        exit;
    }
    $qid = $_POST['qid'];
    $input = $_POST['survey'] ?? '';


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

    $q1 = filter_input(INPUT_POST, 'Q1', FILTER_VALIDATE_INT);
    $q2 = filter_input(INPUT_POST, 'Q2', FILTER_VALIDATE_INT);
    $q3 = filter_input(INPUT_POST, 'Q3', FILTER_VALIDATE_INT);

}

$qualifier = " AND s.surveyId = '${survey}'";


if ($q1 > 0) {
    $qualifier.=" AND r.Q1 = " . $q1;

}

if ($q2 > 0) {
    $qualifier.=" AND r.Q2 = " . $q2; 
}

if ($q3 > 0) {
    $qualifier.=" AND r.Q3 = " . $q3; 
}


// 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);

    $baseSql = "
        SELECT 
        a.value, 
        COUNT(*) AS count 
        FROM Answers a
        INNER JOIN Responses r ON a.responseId = r.id
        INNER JOIN Surveys s ON a.surveyId = s.id
        WHERE a.QID = :qid
    ";

        //GROUP BY a.value, r.Q1, r.Q2, r.Q3
    $sql = $baseSql . $qualifier . "
        GROUP BY a.value
        ORDER BY a.value;
    ";

    //echo $sql;

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

    // Initialize array with all possible values from -3 to 3 with zero counts
    $counts = [];
    for ($i = -3; $i <= 3; $i++) {
        $counts[$i] = 0;
    }

    // Fill in counts from query results
    foreach ($results as $row) {
        $counts[(int)$row['value']] = (int)$row['count'];
    }

    // Return as JSON array of objects [{value: -3, count: 5}, ...]
    $response = [];
    foreach ($counts as $value => $count) {
        //$response[] = ['value' => $value, 'count' => $count];
        $response[] = ['"'.strval($value).'"' => $count];
    }

    echo json_encode($response);

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











