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

if (php_sapi_name() === 'cli') {
    echo "Running from command line.\n";
} else {
    //echo "Running from browser.\n";
    // Basic input validation and sanitization
    if (!isset($_POST['action']) || empty($_POST['qid'])) {
        echo json_encode(['error' => 'Needs an action to carry out']);
        exit;
    }
}


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

    // Map of QIDs to Response columns
    $qidToColumn = [
        'QID68' => 'Q1',
        'QID69' => 'Q2',
        'QID71' => 'Q3'
    ];

    $totalUpdated = 0;

    foreach ($qidToColumn as $qid => $column) {
        $sql = "
            UPDATE Responses r
            JOIN Answers a ON r.id = a.responseId
            SET r.{$column} = a.value
            WHERE a.QID = :qid
              AND r.{$column} IS NULL
        ";

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

        $rows = $stmt->rowCount();
        echo "Updated {$rows} rows for {$qid} → {$column}\n";
        $totalUpdated += $rows;
    }

    echo "Total rows updated: {$totalUpdated}\n";

} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}















