<?php
session_start();

// Reduce execution time limit to 30 seconds
set_time_limit(30);
ini_set('max_execution_time', '30');

// Rate limiting - max 10 requests per minute per user (optional, can be removed for unlimited)
function checkRateLimit() {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'output' => 'Authentication required']);
        exit();
    }

    $user_id = $_SESSION['user_id'];
    $rate_limit_file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'rate_limit_' . $user_id . '.json';

    $current_time = time();
    $rate_data = [];

    if (file_exists($rate_limit_file)) {
        $rate_data = json_decode(file_get_contents($rate_limit_file), true) ?: [];
        $rate_data = array_filter($rate_data, function($timestamp) use ($current_time) {
            return ($current_time - $timestamp) < 60;
        });
    }

    if (count($rate_data) >= 10) {
        $oldest_request = min($rate_data);
        $wait_time = 60 - ($current_time - $oldest_request);
        echo json_encode([
            'success' => false,
            'output' => "Rate limit exceeded! Please wait {$wait_time} seconds before trying again."
        ]);
        exit();
    }

    $rate_data[] = $current_time;
    file_put_contents($rate_limit_file, json_encode($rate_data));
}

checkRateLimit();

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'output' => 'Invalid request method']);
    exit();
}

$code = $_POST['code'] ?? '';

if (empty($code)) {
    echo json_encode(['success' => false, 'output' => 'No code provided']);
    exit();
}

// Piston API endpoint
$PISTON_API_URL = 'https://emkc.org/api/v2/piston/execute';

// Prepare the request data
$request_data = [
    'language' => 'c++',
    'version' => '10.2.0', // GCC 10.2.0
    'files' => [
        [
            'name' => 'main.cpp',
            'content' => $code
        ]
    ],
    'stdin' => '', // Can add input support later
    'args' => [],
    'compile_timeout' => 10000, // 10 seconds
    'run_timeout' => 3000, // 3 seconds
    'compile_memory_limit' => -1,
    'run_memory_limit' => -1
];

// Make the API request
$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => $PISTON_API_URL,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($request_data),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json'
    ],
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);

curl_close($ch);

if ($curl_error) {
    echo json_encode([
        'success' => false,
        'output' => 'Network error: ' . $curl_error
    ]);
    exit();
}

if ($http_code !== 200) {
    echo json_encode([
        'success' => false,
        'output' => 'API Error (HTTP ' . $http_code . '). Please try again.'
    ]);
    exit();
}

$result = json_decode($response, true);

if (!$result) {
    echo json_encode([
        'success' => false,
        'output' => 'Failed to parse API response'
    ]);
    exit();
}

// Process the result
$output = '';
$success = false;

// Check if compilation was successful
if (isset($result['compile']) && !empty($result['compile']['stderr'])) {
    // Compilation error
    $output = "Compilation Error:\n" . $result['compile']['stderr'];
} elseif (isset($result['run'])) {
    // Check runtime result
    $run_result = $result['run'];

    if (!empty($run_result['stdout'])) {
        // Success - has output
        $success = true;
        $output = $run_result['stdout'];
    } elseif (!empty($run_result['stderr'])) {
        // Runtime error
        $output = "Runtime Error:\n" . $run_result['stderr'];
    } elseif ($run_result['code'] === 0) {
        // Success but no output
        $success = true;
        $output = '(Program executed successfully but produced no output)';
    } else {
        // Other error
        $output = "Error: Program exited with code " . $run_result['code'];
        if (!empty($run_result['stderr'])) {
            $output .= "\n" . $run_result['stderr'];
        }
    }
} else {
    $output = 'Unexpected API response';
}

echo json_encode([
    'success' => $success,
    'output' => $output,
    'language' => $result['language'] ?? 'c++',
    'version' => $result['version'] ?? '10.2.0'
]);
?>
