<?php
require_once '../db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['challenge_id'], $_POST['language'], $_POST['solution']) && !empty($_POST['solution'])) {
        $challenge_id = $_POST['challenge_id'];
        $language = $_POST['language'];
        $solution = $_POST['solution'];

        $pdo = db();

        $stmt = $pdo->prepare('SELECT sample_cases_json, expected_output FROM challenges WHERE id = ?');
        $stmt->execute([$challenge_id]);
        $challenge = $stmt->fetch();

        if ($language === 'python') {
            // WARNING: Executing user-submitted code with shell_exec is a major security risk.
            // This should be replaced with a secure sandboxed execution environment.
            $temp_file = tempnam(sys_get_temp_dir(), 'py');
            file_put_contents($temp_file, $solution);
            $output = shell_exec('python3 ' . $temp_file . ' 2>&1');
            unlink($temp_file);

            echo "<pre>" . htmlspecialchars($output) . "</pre>";
        } else {
            echo "<div class=\"alert alert-warning\"> Running code for this language is not yet supported.</div>";
        }
    } else {
        echo "<div class=\"alert alert-danger\"> Please provide a solution.</div>";
    }
} else {
    header('Location: ../challenges.php');
    exit();
}

